UITextView 自帶 URL 偵測功能,開啟後會把內容中的網址高亮顯示,點擊則由 Safari 開啟。但有時候我們想要的不只是開啟瀏覽器——例如點擊「查看詳細說明」跳到 App 內的說明頁,點擊「問題反饋」則進入反饋流程。本文示範如何做到這件事。

讓同一段文字裡的不同片段各自觸發不同行為,而不僅是開啟網頁。

about: 代表詳細說明、feedback: 代表問題反饋。UITextViewDelegate 的 shouldInteractWithURL 方法中攔截點擊事件,依 URL.scheme 分派不同操作。用來顯示的 textView 需勾選 Detection Links(鏈結偵測),並取消 Editable(設為不可編輯)。

extension UITextView {
// 添加連結文字(withURLString 為空時代表普通文字)
func appendLinkString(string: String, withURLString: String = "") {
// 原有的文字內容
let attrString = NSMutableAttributedString()
attrString.appendAttributedString(self.attributedText)
// 新增的文字內容(沿用預設字型樣式)
let attrs = [NSFontAttributeName: self.font!]
let appendString = NSMutableAttributedString(string: string, attributes: attrs)
// 判斷是否為連結文字
if withURLString != "" {
let range = NSMakeRange(0, appendString.length)
appendString.beginEditing()
appendString.addAttribute(NSLinkAttributeName, value: withURLString, range: range)
appendString.endEditing()
}
// 合併並重新賦值
attrString.appendAttributedString(appendString)
self.attributedText = attrString
}
}
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)
}
}
這套做法的價值在於「用同一個 textView 承載多種互動」。除了跳轉頁面,你還可以在 scheme 後面帶上參數(如範例中的 from123),在回呼時解析並據以決定後續行為,靈活度相當高。
原文出自:www.hangge.com