Detecting special character tap in UITextView [Swift]

I am trying to create a UITextView in iOS8 that recognizes clicks on certain words, specifically the words preceding the "#" and "@" characters

I first tried the following method on a UITextView subclass:

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 text view will print the word but will not contain "#" and "@", I believe this is due to the verbosity of .Word not recognizing special characters. I came up with a work-around that uses attributed text to define a special character prefix.

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 it works really well, but clicking on a special character won't print the word. Does anyone have a possible solution to this problem? Is there another way to identify pressed words without using it rangeEnclosingPosition

?

+3


source to share





All Articles