我如何以正确的方式实现委托方法?

时间:2016-04-15 09:27:39

标签: ios iphone swift uiview uiviewcontroller

我目前正在使用Swift开发iOS应用。 我已经实现了一个定制的UIView,它是对ViewController的addSubview-ed,并且在ViewController中有一个委托方法,它是从定制的UIView中的UIButton调用的。

当我实现委托方法时,因为它直接从CustomView调用,我收到一个错误,说明"无法识别的选择器被发送到实例xxxx"。我认为存储容量存在问题。

SampleViewController

class SampleViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let customView = CustomView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
        self.view.addSubview(customView) 
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func sampleFunc() {
        print("sampleFunc")
    }
}

CustomView

class CustomView: UIView {
    let button = UIButton(frame: CGRectZero)

    func setup() {
        button.addTarget(self, action: #selector(SampleViewController.sampleFunc(_:)), forControlEvents: .TouchUpInside)
        self.addSubview(button)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        // 
    }
}

但另一方面,如果我以类似于下面的方式从CustomView调用方式实现该方法,它就像我预期的那样工作。

CustomView(修改)

class CustomView: UIView {
    let button = UIButton(frame: CGRectZero)

    func setup() {
        button.addTarget(self, action: #selector(CustomView.buttonAction(_:)), forControlEvents: .TouchUpInside)
        self.addSubview(button)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        // 略
    }

    @objc private func buttonAction(sender: AnyObject) {
        UIApplication.sharedApplication().sendAction(#selector(SampleViewController.sampleFunc(_:)), to: nil, from: self, forEvent: nil)
    }

}

问题是如果我以间接调用的方式实现方法,我就不明白为什么它能够正常工作。我感谢所有的帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

 button.addTarget(self, action: #selector(SampleViewController.sampleFunc(_:)), forControlEvents: .TouchUpInside)

此行表示当您点按按钮时,它应该在selfCustomView)和selfCustomView)上查看并执行方法,不提供任何实施sampleFunc,在第二种情况下,你已经在那里实现了方法并且它的工作正常,。在viewController方法中传递self个对象而不是addTarget

您可以在viewController object方法中将init作为参数传递,然后在设置方法中使用该方法。