Get to UIViewController from UIView?

前端 未结 29 2024
一整个雨季
一整个雨季 2020-11-22 16:57

Is there a built-in way to get from a UIView to its UIViewController? I know you can get from UIViewController to its UIView

29条回答
  •  一个人的身影
    2020-11-22 17:41

    I stumbled upon a situation where I have a small component I want to reuse, and added some code in a reusable view itself(it's really not much more than a button that opens a PopoverController).

    While this works fine in the iPad (the UIPopoverController presents itself, therefor needs no reference to a UIViewController), getting the same code to work means suddenly referencing your presentViewController from your UIViewController. Kinda inconsistent right?

    Like mentioned before, it's not the best approach to have logic in your UIView. But it felt really useless to wrap the few lines of code needed in a separate controller.

    Either way, here's a swift solution, which adds a new property to any UIView:

    extension UIView {
    
        var viewController: UIViewController? {
    
            var responder: UIResponder? = self
    
            while responder != nil {
    
                if let responder = responder as? UIViewController {
                    return responder
                }
                responder = responder?.nextResponder()
            }
            return nil
        }
    }
    

提交回复
热议问题