NSMutableAttributedString 中的可单击链接需要显示另一个视图控制器/情节提要



我有一个UITextView和NSMutableAttributedString,它有一个可点击的链接。我需要这个来显示另一个故事板,但不太确定我该怎么做。

到目前为止,我所拥有的适用于外部链接,但不适用于故事板。任何帮助将不胜感激。

不确定下面的代码是否是最好的方法?

class HomeViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let attributedString = NSMutableAttributedString(string: "Already have an account? Log in")
attributedString.addAttribute(.link, value: "", range: NSRange(location: 25, length: 6))
textView.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
UIApplication.shared.open(URL)
return false
}

}

编辑

在 NikR 回答后,我已经将我的代码更新为以下内容,但仍然没有成功。它仍在加载谷歌。

class HomeViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let attributedString = NSMutableAttributedString(string: "Already have an account? Log in")
attributedString.addAttribute(.link, value: "https://google.com", range: NSRange(location: 25, length: 6))
textView.attributedText = attributedString
textView.isSelectable = true
textView.isEditable = false
textView.delegate = self
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
let loginViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loginViewController")
show(loginViewController, sender: self)
return true
}

}

是的,这是正确的方法。 但不要打电话:

UIApplication.shared.open(URL)

只需启动您的 VC 并展示/演示它:

let vc = UIStoryboard(name: "StoryboardName", bundle: nil).instantiateInitialViewController()
show( vc, sender: self )

并且不要忘记:

textView.delegate = self

您可以设置为文本视图:

textView.dataDetectorTypes = .link

您应该为文本视图启用 isSelectable 并禁用 isEditable。

textView.isSelectable = true
textView.isEditable = false

不要忘记这样做

textView.delegate = self

此委托方法将用于处理单击

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
}

最新更新