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
For Swift 3 +
extension UITextView {
func convertHashtags(text:String) -> NSAttributedString {
let attr = [
NSFontAttributeName : UIFont.systemFont(ofSize: 17.0),
NSForegroundColorAttributeName : clr_golden,
NSLinkAttributeName : "https://Laitkor.com"
] as [String : Any]
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: NSRegularExpression.Options.anchorsMatchLines)
let results = regex.matches(in: text,
options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, text.characters.count))
let array = results.map { (text as NSString).substring(with: $0.range) }
for hashtag in array {
// get range of the hashtag in the main string
let range = (attrString.string as NSString).range(of: hashtag)
// add a colour to the hashtag
//attrString.addAttribute(NSForegroundColorAttributeName, value: clr_golden , range: range)
attrString.addAttributes(attr, range: range)
}
attrString.endEditing()
}
catch {
attrString.endEditing()
}
return attrString
}
}
Add UITextViewDelegate in your class and Use like this
self.tv_yourTextView.delegate = self
self.tv_yourTextView.attributedText = tv_yourTextView.convertHashtags(text: "This is an #museer test")
delegate funtion
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
print("hastag Selected!")
return true
}
-> Modified @Wez Answer