將一段文字中的某長度字符串設置成可點擊的富文本青团,如將下面的一段文本中的點電話號碼設置成可點擊督笆,并調用系統(tǒng)打電話功能撥號的效果
let string ="您可以直接撥打預約電話聯系咨詢娃肿,客服電話400-000-000"
letattributedString =NSMutableAttributedString.init(string: string)
attributedString.addAttribute(NSLinkAttributeName, value:"400-000-000", range:NSRange(location:19,length:11))
textView=UITextView(frame:CGRect(x:100,y:100,width:150,height:30))
textView?.linkTextAttributes= [NSForegroundColorAttributeName:UIColor.blue]
textView?.font=UIFont.systemFont(ofSize:12)
textView?.textColor=UIColor.black
textView?.delegate=self
textView?.attributedText= attributedString
textView?.isEditable=false
self.view.addSubview(textView!)
//實現textView的代理方法料扰,記得遵守textView的代理
func textView(_textView:UITextView, shouldInteractWith URL:URL, in characterRange:NSRange) ->Bool{
let alertController =UIAlertController(title:"提示", message:"確定撥打電話:400-000-000嗎凭豪?", preferredStyle:UIAlertControllerStyle.alert)
letcancelAction =UIAlertAction(title:"取消", style:UIAlertActionStyle.cancel, handler: { (_)in
print("取消")
})
letokAction =UIAlertAction(title:"好的", style:UIAlertActionStyle.default, handler: { (_)in
print("確定")
UIApplication.shared.openURL(NSURL(string:"tel://"+"400000000")!asURL)
})
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.present(alertController, animated:true, completion:nil)
return true
}
小結:一定要使用textView來設置,并且把textView的isEnable設置成false