swift3.0 將一段文本中的若干個字符設置成可點擊的富文本

將一段文字中的某長度字符串設置成可點擊的富文本,如將下面的一段文本中的點電話號碼設置成可點擊,并調用系統打電話功能撥號的效果

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容