我们知道多行文本框(UITextView)具有URL检测功能,将其开启后,它会高亮显示内容中的url链接文字,点击后会使用safari打开这个链接。
1,让textView支持自定义链接
除了能够用浏览器打开url链接外,有时我们还想让内容中的链接能实现一些个性化的功能需求。比如:点击“查看详细说明”后,APP会跳转到功能说明页面。而点击“问题反馈”链接时,又会到进行问题反馈操作。
2,实现原理:
(1)对于这些特殊的链接我们使用自定义的一些 URL scheme 来表示。比如:about:代表详细说明,feedback:代表问题反馈。
(2)通过拼接 NSMutableAttributedString 的方式,将各个带链接属性、不带链接属性的文本拼接起来,赋值给textview。
(3)使用textview的 UITextFieldDelegate 代理的 shouldInteractWithURL 方法,我们可以捕获到这些自定义的URL scheme点击,然后通过判断 URL.scheme 来执行不同的操作。
3,实现步骤
(1)对于用来显示的textview,要将其 Detection Links(链接检测)打勾,去掉 Editable(使其不可编辑)。
(2)为方便使用,扩展UITextView:
extension UITextView {
//添加链接文本(链接为空时则表示普通文本)
func appendLinkString(string:String, withURLString:String = "") {
//原来的文本内容
let attrString:NSMutableAttributedString = NSMutableAttributedString()
attrString.appendAttributedString(self.attributedText)
//新增的文本内容(使用默认设置的字体样式)
let attrs = [NSFontAttributeName : self.font!]
let appendString = NSMutableAttributedString(string: string, attributes:attrs)
//判断是否是链接文字
if withURLString != "" {
let range:NSRange = NSMakeRange(0, appendString.length)
appendString.beginEditing()
appendString.addAttribute(NSLinkAttributeName, value:withURLString, range:range)
appendString.endEditing()
}
//合并新的文本
attrString.appendAttributedString(appendString)
//设置合并后的文本
self.attributedText = attrString
}
}
(3)样例代码 :
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
//设置展示文本框的代理
textView.delegate = self
textView.text = ""
textView.appendLinkString("欢迎使用航歌APP!\n")
textView.appendLinkString("(1)")
textView.appendLinkString("查看详细说明", withURLString: "about:from123")
textView.appendLinkString("\n(2)")
textView.appendLinkString("问题反馈", withURLString: "feedback:from234")
}
//链接点击响应方法
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL,
inRange characterRange: NSRange) -> Bool {
switch URL.scheme {
case "about" :
showAlert("about",
payload: URL.resourceSpecifier.stringByRemovingPercentEncoding!)
case "feedback" :
showAlert("feedback",
payload: URL.resourceSpecifier.stringByRemovingPercentEncoding!)
default:
print("这个是普通的url")
}
return true
}
//显示消息
func showAlert(tagType:String, payload:String){
let alertController = UIAlertController(title: "检测到\(tagType)标签",
message: payload, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "确定", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
原文出自:www.hangge.com
[swift code]Swift给UITextView添加自定义链接,以及链接的点击响应例子
http://m.bbyears.com/wangyetexiao/96323.html
推荐访问:swift代码