Open eliburke opened 6 years ago
I should add.. if you want to play with this without merging #657, you can add this in your SLKTextViewController subclass:
public func acceptAutoCompletion(attributedString: NSAttributedString, keepPrefix: Bool) {
if attributedString.length == 0 {
return
}
var location = self.foundPrefixRange.location
if (keepPrefix) {
location += self.foundPrefixRange.length
}
var length = self.foundWord?.lengthOfBytes(using: .utf8) ?? 0
if (!keepPrefix) {
length += self.foundPrefixRange.length
}
let range = NSMakeRange(location, length)
let insertionRange = textView.slk_insertAttributedText(attributedString, in: range)
self.textView.selectedRange = NSMakeRange(insertionRange.location, 0);
self.textView.slk_scrollToCaretPositon(animated: false)
self.cancelAutoCompletion()
}
I submitted PR #657 to allow autocomplete to submit attributed strings. The goal is to implement mentions in a more seamless manner. Here's a short gif showing improved handling. I think the majority of this could be incorporated into the framework if there is desire.
Here's my current implementation. Apologies if you don't know Swift; it should not be too hard to translate back to Objective C.
First, a global constant:
let MentionAttributeStringKey = NSAttributedStringKey(rawValue: "UserMention")
A helper to generate the attributed text tags for a new mention token
The meat of this feature is additional logic for SLKTextView's shouldChangeTextIn delegate. Here I override the implementation, and fall through to super if no mention token is being modified.
After a token is detected (by looking for the custom
MentionAttributeStringKey
I first strip off all added attributes. This helps prevent styling future text entry incorrectly. Then I replace the selection with the desired text (unless they hit backspace-- a completely empty textView seems to incorrectly preserve some undesired text attributes, so I insert a space). Finally, place the cursor within the updated string.The next piece of the puzzle is to update your didSelectRowAt, where the code processes selection of autocomplete entries:
After this, things will become more customized based on your application and messaging protocol. When the user hits send, use
textView.attributedText.enumerateAttribute
to enumerate mentions and handle accordingly. You may probably need to do text substitutions or some other protocol-specific processing, both for sending the message and for displaying in text bubbles.I hope this is useful for folks, and if the repo maintainers are interested in incorporating it, I'm happy to be involved.