问题从IBAction调用外部分配的关闭

时间:2017-02-14 15:48:22

标签: ios swift swift3

我有这个UIView子类:

class EmptyAlbumsView: UIView {

class func instanceFromNib() -> EmptyAlbumsView {
    return R.nib.emptyAlbumsView.firstView(owner: nil)! as EmptyAlbumsView
}

// MARK: - IBActions

@IBAction func didTapFreeAlbumButton(sender: UIButton) {
    print("Tapping button")
    print(didTapFreeAlbumButtonClosure)
    didTapFreeAlbumButtonClosure?()
}

@IBAction func didTapEventAlbumButton(sender: UIButton) {
    didTapEventAlbumButtonClosure?()
}

@IBAction func didTapWhatsTheDifferenceButton(sender: UIButton) {
    didTapWhatsTheDifferenceButtonClosure?()
}

@IBAction func didTapSubmitAlbumCodeButton(sender: UIButton) {
    didTapSubmitAlbumCodeButtonClosure?()
}

// MARK: - Public Properties
open var didTapFreeAlbumButtonClosure: EmptyClosure? {
    didSet {
        log.verbose("set to \(self.didTapFreeAlbumButtonClosure!)")
    }
}

open var didTapEventAlbumButtonClosure: EmptyClosure?
open var didTapWhatsTheDifferenceButtonClosure: EmptyClosure?
open var didTapSubmitAlbumCodeButtonClosure: EmptyClosure?

}

我正在UIViewController中初始化:

 fileprivate func showEmptyAlbumsView() {

    let emptyAlbumsView = EmptyAlbumsView.instanceFromNib()

    emptyAlbumsView.didTapFreeAlbumButtonClosure = {
        print("hey")
    }

    view.addSubview(emptyAlbumsView)
    emptyAlbumsView.matchEdgeAnchorsOfView(self.view)

}

我可以看到来自Tapping button的{​​{1}}日志语句,但是那里的第二个日志语句打印IBAction,因为看起来nil尚未设置,并且当然不会被称为永远。我从来没有看到didTapFreeAlbumButtonClosure打印出来。

但是,在hey块中,我可以清楚地看到闭包已经设置好了。

didSet定义为EmptyClosure

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

好的,经过很多挫折后,问题相当愚蠢。

在Interface Builder中,我将my xib的File Owner设置为EmptyAlbumsView。这导致IBActions被正确调用,但当我尝试连接一些IBOutlets时,我得到了KVC错误。

看来正确的方法是将File Owner类留空,并将xib的根视图设置为EmptyAlbumsView。然后我将IBOutlets和IBActions直接挂钩到视图中。