UITextView shouldInteractWith 委托在警报完成时返回值
UITextView shouldInteractWith delegate returning value in alert completion
我在可以包含 URL 的 table 视图单元格中有一个文本视图。当用户点击 URL 时,我想发出警报以确保用户在处理 URL 之前想要继续。我试图在适当的委托方法中实现它,但我被卡住了,因为 return 值不能在警报的完成块中。在使用此方法 return 之前如何等待用户做出选择?
相关代码:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
var alert = UIAlertController(title: "Are you sure?", message: "You are about to leave the app to open an external link", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
alert.dismiss(animated: true) {
// return true would go here
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
alert.dismiss(animated: true) {
// return false would go here
}
}
alert.addAction(cancelAction)
alert.addAction(yesAction)
UIApplication.shared.firstKeyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
// Traditionally the return should go here
}
让代表等待响应是不好的做法。我的解决方案是
alert.dismiss(animated: true) {
UIApplication.shared.open(url)
}
并向委托人返回 false。这样我就把 URL 处理留给我的代码而不是 iOS 本机行为
我在可以包含 URL 的 table 视图单元格中有一个文本视图。当用户点击 URL 时,我想发出警报以确保用户在处理 URL 之前想要继续。我试图在适当的委托方法中实现它,但我被卡住了,因为 return 值不能在警报的完成块中。在使用此方法 return 之前如何等待用户做出选择?
相关代码:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
var alert = UIAlertController(title: "Are you sure?", message: "You are about to leave the app to open an external link", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
alert.dismiss(animated: true) {
// return true would go here
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
alert.dismiss(animated: true) {
// return false would go here
}
}
alert.addAction(cancelAction)
alert.addAction(yesAction)
UIApplication.shared.firstKeyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
// Traditionally the return should go here
}
让代表等待响应是不好的做法。我的解决方案是
alert.dismiss(animated: true) {
UIApplication.shared.open(url)
}
并向委托人返回 false。这样我就把 URL 处理留给我的代码而不是 iOS 本机行为