我有这个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
我在这里缺少什么?
答案 0 :(得分:1)
好的,经过很多挫折后,问题相当愚蠢。
在Interface Builder中,我将my xib的File Owner
设置为EmptyAlbumsView
。这导致IBActions
被正确调用,但当我尝试连接一些IBOutlets
时,我得到了KVC错误。
看来正确的方法是将File Owner
类留空,并将xib的根视图设置为EmptyAlbumsView
。然后我将IBOutlets和IBActions直接挂钩到视图中。