. UITextView, , ( , ).
, .blueColor(), , , , .
Twitter #1 @abc.go.
:
https://github.com/ThornTechPublic/SwiftTextViewHashtag/blob/master/textViewSample/UITextField%2BExtension.swift
:
http://www.thorntech.com/2015/06/detecting-hashtags-mentions-and-urls-with-swift/
extension UITextView {
func chopOffNonAlphaNumericCharacters(text:String) -> String {
var nonAlphaNumericCharacters = NSCharacterSet.alphanumericCharacterSet().invertedSet
let characterArray = text.componentsSeparatedByCharactersInSet(nonAlphaNumericCharacters)
return characterArray[0]
}
func resolveHashTags(){
let schemeMap = [
"#":"hash",
"@":"mention"
]
let nsText:NSString = self.text
let words:[NSString] = nsText.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) as! [NSString]
var attrs = [
NSFontAttributeName : UIFont.systemFontOfSize(17.0)
]
var attrString = NSMutableAttributedString(string: nsText as String, attributes:attrs)
for word in words {
var scheme:String? = nil
if word.hasPrefix("#") {
scheme = schemeMap["#"]
} else if word.hasPrefix("@") {
scheme = schemeMap["@"]
}
if let scheme = scheme {
var stringifiedWord:String = word as String
stringifiedWord = dropFirst(stringifiedWord)
stringifiedWord = chopOffNonAlphaNumericCharacters(stringifiedWord)
if let stringIsNumeric = stringifiedWord.toInt() {
} else if stringifiedWord.isEmpty {
} else {
var matchRange:NSRange = nsText.rangeOfString(stringifiedWord as String)
matchRange.location--
matchRange.length++
attrString.addAttribute(NSLinkAttributeName, value: "\(scheme):\(stringifiedWord)", range: matchRange)
}
}
}
self.attributedText = attrString
}
}
:
textView.resolveHashTags()
:
func showHashTagAlert(tagType:String, payload:String){
let alertView = UIAlertView()
alertView.title = "\(tagType) tag detected"
alertView.message = "\(payload)"
alertView.addButtonWithTitle("Ok")
alertView.show()
}
extension ViewController : UITextViewDelegate {
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
if let scheme = URL.scheme {
switch scheme {
case "hash" :
showHashTagAlert("hash", payload: URL.resourceSpecifier!)
case "mention" :
showHashTagAlert("mention", payload: URL.resourceSpecifier!)
default:
println("just a regular url")
}
}
return true
}
}