I'm trying to build a UITextView in iOS8 that recognizes taps on specific words, specifically words preceded by the "#" and "@ symbols"
I first tried the following method in a subclass of UITextView:
var point = tapGesture.locationInView(self)
var position = closestPositionToPoint(point)
let range = tokenizer.rangeEnclosingPosition(position, withGranularity: .Word, inDirection: 1)
let word = textInRange(range)
println(word!)
However, clicking on a word in a text view prints the word, but will leave out the "#" and "@", I believe this to be from the .Word granularity not recognizing special characters. I came up with a work around that uses attributed text to identify the prefixed special character.
var point = tapGesture.locationInView(self)
var position = closestPositionToPoint(point)
let range = tokenizer.rangeEnclosingPosition(position, withGranularity: .Word, inDirection: 1)
if range != nil {
let location = offsetFromPosition(beginningOfDocument, toPosition: range!.start)
let length = offsetFromPosition(range!.start, toPosition: range!.end)
let attrRange = NSMakeRange(location, length)
let attrText = attributedText.attributedSubstringFromRange(attrRange)
let word = attributedText.attributedSubstringFromRange(attrRange)
let isHashtag: AnyObject? = word.attribute("Hashtag", atIndex: 0, longestEffectiveRange: nil, inRange: NSMakeRange(0, word.length))
let isAtMention: AnyObject? = word.attribute("Mention", atIndex: 0, longestEffectiveRange: nil, inRange: NSMakeRange(0, word.length))
if isHashtag != nil {
println("#\(word.string)")
} else if isAtMention != nil {
println("@\(word.string)")
}
}
And this works pretty well, but tapping on the special character will not print out the word. Does anyone have possible solution to this problem? Is there a different way to identify tapped words without using rangeEnclosingPosition
?