Với Swift 3, UITextViewDelegate
cung cấp một phương pháp textView(_:shouldInteractWith:in:interaction:)
. textView(_:shouldInteractWith:in:interaction:)
có tuyên bố sau:
Yêu cầu đại biểu nếu chế độ xem văn bản được chỉ định sẽ cho phép loại người dùng được chỉ định tương tác với URL đã cho trong phạm vi văn bản nhất định.
optional func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool
Các mã sau đây cho thấy làm thế nào để mở UITextView
liên kết web trong một SFSafariViewController
thay vì mở chúng trong Safari ứng dụng:
import UIKit
import SafariServices
class ViewController: UIViewController, UITextViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Set textView
let textView = UITextView()
textView.text = "http://www.yahoo.fr http://www.google.fr"
textView.isUserInteractionEnabled = true
textView.isEditable = false
textView.isSelectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.link
// Add view controller as the textView's delegate
textView.delegate = self
// auto layout
view.addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
textView.heightAnchor.constraint(equalToConstant: 300).isActive = true
textView.widthAnchor.constraint(equalToConstant: 300).isActive = true
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
// Open links with a SFSafariViewController instance and return false to prevent the system to open Safari app
let safariViewController = SFSafariViewController(url: URL)
present(safariViewController, animated: true, completion: nil)
return false
}
}
Nguồn
2017-01-24 14:06:09
Uhm, là riêng, bạn có nghĩ nó sẽ là một vấn đề cho sự chấp thuận của Appstore? Btw tối nay tôi sẽ kiểm tra mã của bạn và tôi sẽ cho bạn biết. Cảm ơn. – crash
Đây không phải là thứ mà họ có thể kiểm tra, nhưng bạn có thể có nguy cơ thay đổi hệ điều hành trong tương lai (đây là API công khai trong tương đương với máy tính và không chắc Apple sẽ ngừng sử dụng WebKit, nhưng có thể) . Điều tồi tệ nhất có thể xảy ra là hành vi sẽ trở lại mặc định khi khởi chạy MobileSafari. – rpetrich
Hoàn hảo. Nó hoạt động trơn tru. Cảm ơn! – crash