代表在调用swift后不执行

时间:2018-03-09 15:21:34

标签: ios swift class delegates protocols

我有一个viewController,其中另一个containerView内部设置为临时显示(以编程方式添加)。 containerView是一种操作栏,允许您更改viewController的值。但是,从按钮的IBAction调用的协议不会调用viewController类中设置的协议。

以下是两个类的代码:

class viewController: UIViewController, updateListDelegate {
    let dataSource = containerView()

    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource.delegate = self
    }

    func updateList(sender: containerView) {
        print("is called") //is not printed
    }
}

containerView的代码:

protocol updateListDelegate {
    func updateList(containerView)
}

class containerView: UIViewController {
    var delegate: updateListDelegate?

    @IBAction func AddSong(_ sender: UIButton) {
        self.delegate?.updateList(sender: self)
    }
}

1 个答案:

答案 0 :(得分:1)

If this method is only to be called from one object, then, in my opinion, I would not define a protocol. If multiple objects are to call this method, then I would define a protocol. This is typically how you would call a method backwards, using a basic delegate.

class ViewController: UIViewController {

    let container = ContainerView()

    override func viewDidLoad() {
        super.viewDidLoad()

        container.viewControllerDelegate = self
        // push to this instance of container at some point

    }

    func doSomething() {
        print("great success")
    }

}


class ContainerView: UIViewController {

    weak var viewControllerDelegate: ViewController?

    @objc func someAction() {
        if let viewControllerDelegate = viewControllerDelegate {
            viewControllerDelegate.doSomething()
        }
    }

}

// prints "great success" when someAction() called

One of the most common mistakes people make is not keeping track of instances. For delegates to work, you must be sure you are using the specific instances that you've instantiated and assigned those delegates to.