Swift 4.2 Xcode 10.1
func setupContactUsTextView() {
let text = NSMutableAttributedString(string: "Love your App, but need more help? Text, Call (123) 456-1234 or email ")
if let font = UIFont(name: "Calibri", size: 17) {
text.addAttribute(NSAttributedStringKey.font,
value: font,
range: NSRange(location: 0, length: text.length))
} else {
text.addAttribute(NSAttributedStringKey.font,
value: UIFont.systemFont(ofSize: 17),
range: NSRange(location: 0, length: text.length))
}
text.addAttribute(NSAttributedStringKey.foregroundColor,
value: UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0),
range: NSRange(location: 0, length: text.length))
text.addAttribute(NSAttributedStringKey.link, value: "tel://", range: NSRange(location: 49, length: 15))
let interactableText = NSMutableAttributedString(string: "contact@abc.com")
if let font = UIFont(name: "Calibri", size: 17) {
interactableText.addAttribute(NSAttributedStringKey.font,
value: font,
range: NSRange(location: 0, length: interactableText.length))
} else {
interactableText.addAttribute(NSAttributedStringKey.font,
value: UIFont.systemFont(ofSize: 17),
range: NSRange(location: 0, length: interactableText.length))
}
interactableText.addAttribute(NSAttributedStringKey.link,
value: "contact@abc.com",
range: NSRange(location: 0, length: interactableText.length))
interactableText.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: NSRange(location: 0, length: interactableText.length))
text.append(interactableText)
videoDescTextView.attributedText = text
videoDescTextView.textAlignment = .center
videoDescTextView.isEditable = false
videoDescTextView.isSelectable = true
videoDescTextView.delegate = self
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (characterRange.location > 48 && characterRange.location < 65){
print("open phone")
}else{
print("open gmail")
}
return false
}
Steps -
1. Set the delegate to your text field and don't forget to implement UITextViewDelegate
2. Take the textView outlet - @IBOutlet weak var videoDescTextView: UITextView!
3. Add these two functions given above.
This function shows how to detect phone numbers, email from textView, how to underline your email id, how to give custom color to your text, custom font, how to call a function when tapping on phone or email, etc.
Hope this will help someone to save their valuable time. Happy Coding :)