What you want to do is use an attributed string with a text view to make a link that will act as a button.
let attributedString = NSMutableAttributedString(string: "Some string with link", attributes: [])
Then set a part of it as a link, and customize it's appearance using the linkAttributes
property of the Text View. Because this is a button and not an actual link we just put a dummy url in for the link so we can handle it in our delegate later.
attributedString.setSubstringAsLink(substring: "link", linkURL: "CUSTOM://WHATEVER")
let linkAttributes: [String : AnyObject] = [NSForegroundColorAttributeName : .redColor(), NSUnderlineColorAttributeName : .redColor(), NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue]
textView.linkTextAttributes = linkAttributes
textView.attributedText = attributedString
textView.selectable = true
textView.editable = false
textView.userInteractionEnabled = true
Finally in text view delegate we will check for the scheme and perform some action.
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
if URL.scheme == "CUSTOM" {
// Do your button actions here
}
return true
}
Extension for setSubstringAsLink:
extension NSMutableAttributedString {
// Set part of string as URL
public func setSubstringAsLink(substring substring: String, linkURL: String) -> Bool {
let range = self.mutableString.rangeOfString(substring)
if range.location != NSNotFound {
self.addAttribute(NSLinkAttributeName, value: linkURL, range: range)
return true
}
return false
}
}