将一段文字中的某长度字符串设置成可点击的富文本,如将下面的一段文本中的点电话号码设置成可点击,并调用系统打电话功能拨号的效果
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