【问题标题】:How to call a method/an action inside UIViewController from custom UIView?如何从自定义 UIView 调用 UIViewController 内的方法/动作?
【发布时间】:2018-10-26 08:26:37
【问题描述】:

在我的 iOS 项目中,在 Swift 中,我有一个自定义的 UIView,其中包括一个 Button。 这个视图是 UIViewController 视图的一部分。 当我从自定义视图中触摸按钮时,我想在 UIViewController 中触发一个方法。

这样做的最佳做法是什么?

【问题讨论】:

    标签: ios swift uiview uiviewcontroller action


    【解决方案1】:

    使用协议/委托:

    protocol TapHandler {
    func tapped()
    }
    
    
    class MyView: UIVieww {
    weak var tapHandler: TapHandler?
    
    /// button tap handler
    @obj func yourTapFunctionInsideView() {
    tapHandler?.tap()
    }
    }
    
    class MyViewController: UIViewController, TapHandler {
    var view: MyView?
    
    override func viewDidLoad() {
    super.viewDidLoad()
    view?.tapHandler = self
    }
    
    func tapped() {
    /// tapped
    }
    }
    

    【讨论】:

    • 不会view.tapHandler = self 崩溃 因为您还没有实例化view?只是问!
    • @ShubhamBakshi 我亲爱的朋友。这段代码甚至不会被编译。显然,这是一个错字。
    • 是的,好的,谢谢:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    相关资源
    最近更新 更多