3
外部分配關閉我有這個UIView
子類:問題調用從IBAction爲
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)
}
我可以從IBAction
看到Tapping button
日誌語句,但在那裏的第二個日誌語句打印nil
,因爲它看起來didTapFreeAlbumButtonClosure
尚未設置,當然也沒有被調用過。我從來沒有看到hey
打印出來。
但是,在didSet
塊中,我可以清楚地看到關閉正在設置。
EmptyClosure
被定義爲typealias EmptyClosure =() ->()
缺少什麼我在這裏?
也許你的閉包變量需要用@objc標記。 –
你是什麼意思? – Thanos
我沒有看到你的代碼有什麼問題。但是關閉沒有被調用一定有一些原因。我猜測可能有一個發現Swift結束的問題。 –