Swift - 在扩展函数中呈现 UIAlertController

标签 swift function label uialertcontroller

我写了一个标签扩展来检测标签中的链接。 它是带有 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/

相关文章:

swift - 如何在 SpriteKit 的不同类中访问已更改的属性

ios - 在 Swift 中解析 PFCloud 问题

swift - 使用swift在背景图像上显示uibutton文本

ios - HackerRink 解决方案重构代码 (Swift)

node.js - 如何从给定 ID 获取用户信息并使用 Node.js 和 EJS 显示它

bash - Bash 中的 Shellshock 漏洞背后的行为是记录在案还是完全是故意的?

java - 调用具有简单返回的函数与仅进行检查有区别吗?

jquery - 将文本添加到一系列标签

javascript - 使用 JavaScript 更改标签文本

d3.js - 通过D3过渡逐渐更改显示为svg文本的数字