I know that the UITextView
default can detect URL, but how can i make it detect hashtags(#)?
It doesn\'t needs to detect hashtags while typing, but then
One option would be to use an NSAttributedString
, something like this...
func convertHashtags(text:String) -> NSAttributedString {
let attrString = NSMutableAttributedString(string: text)
attrString.beginEditing()
// match all hashtags
do {
// Find all the hashtags in our string
let regex = try NSRegularExpression(pattern: "(?:\\s|^)(#(?:[a-zA-Z].*?|\\d+[a-zA-Z]+.*?))\\b", options: NSRegularExpressionOptions.AnchorsMatchLines)
let results = regex.matchesInString(text,
options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, text.characters.count))
let array = results.map { (text as NSString).substringWithRange($0.range) }
for hashtag in array {
// get range of the hashtag in the main string
let range = (attrString.string as NSString).rangeOfString(hashtag)
// add a colour to the hashtag
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
}
attrString.endEditing()
}
catch {
attrString.endEditing()
}
return attrString
}
Then assign your attributedText
like this...
let myText = "some text with a #hashtag in side of it #itsnoteasy"
self.textView.attributedText = convertHashtags(myText)