我写了一个标签扩展来检测标签中的链接。
它是带有 NSLinkAttributeName 链接的属性文本,我正在使用
func handleTapOnLabel(_ tapGesture:UITapGestureRecognizer){}
检测点击的位置以及选择打开哪个链接。问题是我在 UILabel 的扩展中使用了这个函数,我想展示一个 UIAlertController 来问这个人——“你将要在 Safari 中打开这个链接。你想继续吗?”……所以我不能访问 viewcontroller 以使用函数 present(UIAlertController...
显示警报。任何建议如何在扩展中发生这种情况?如何直接从扩展访问标签的 viewcontroller?
最佳答案
方法 1) 在 ViewController 的层次结构中将 UIAlertController 呈现在最顶层的 ViewController
extension UILabel { //your extension
func openLinkAction() { //your extension custom method
//code
if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
}
// topController should now be your topmost view controller
// present alert on this controller
}
//and present here with vcInstance
}
}
方法2)将ViewController的对象作为参数传递
extension UILabel { //your extension
func openLink(vc: UIViewController) { //your extension custom method function
// code
// present alert on this vc
}
}
//为了获得最顶级的 Controller ,你可以使用..
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
// topController
if let topController = UIApplication.topViewController() {
}
关于Swift - 在扩展函数中呈现 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44364679/