![](/img/trans.png)
[英]UIControl not recognizing tap inside table view cell, stopped working from iOS 14
[英]Why is the new iOS 14 UIControl action syntax so terrible?
iOS 14 中的新功能,我們可以將操作處理程序直接附加到 UIControl:
let action = UIAction(title:"") { action in
print("howdy!")
}
button.addAction(action, for: .touchUpInside)
這很酷,但語法令人憤怒。 我必須先形成 UIAction。 我必須給 UIAction 一個標題,即使該標題永遠不會出現在界面中。 沒有更好的方法嗎?
首先,您不需要提供標題。 這是(現在)合法的:
let action = UIAction { action in
print("howdy!")
}
button.addAction(action, for: .touchUpInside)
其次,你真的不需要單獨的行來定義動作,所以你可以這樣說:
button.addAction(.init { action in
print("howdy!")
}, for: .touchUpInside)
然而,這仍然令人憤怒,因為現在我在addAction
調用的中間有一個閉包。 它應該是一個尾隨閉包:顯而易見的解決方案是擴展:
extension UIControl {
func addAction(for event: UIControl.Event, handler: @escaping UIActionHandler) {
self.addAction(UIAction(handler:handler), for:event)
}
}
問題解決了:現在我可以用我應該一直被允許的方式說話了:
button.addAction(for: .touchUpInside) { action in
print("howdy!")
}
[額外信息:這個故事的sender
在哪里? 它在行動里面。 UIAction 有一個sender
屬性。 所以在該代碼中, action.sender
是 UIButton。]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.