我們可以這樣初始化一個新的 UIButton:
// myAction is a var of type UIAction
let btn = UIButton(primaryAction: myAction)
所以我想很酷,我可以將其子類化并停止使用目標操作。但問題來了,Xcode 似乎無法識別primaryAction初始值設定項。
class Button: UIButton {
init(type: String, action: UIAction) {
super.init(primaryAction: action) // Error "Must call a designated initializer of the superclass 'UIButton'"
}
}
所以它不是一個指定的初始化程式。如何在 UIButton 子類中訪問這個 primaryAction 屬性?
uj5u.com熱心網友回復:
因為您不能在自定義初始化程式中使用其便利初始化程式之一初始化超類,所以您必須手動執行該便利初始化程式的任務。因此,在使用其指定的初始化之一初始化超類之后:
class Button: UIButton {
init(type: String, action: UIAction) {
super.init(frame: .zero)
// register the action for the primaryActionTriggered control event
// and set the title and image properties to the action’s title and image
}
}
而且它不像更改單個屬性的值那么簡單。
您可以設定一個控制元件,以便它通過將目標和操作與一個或多個控制元件事件相關聯來向目標物件發送操作訊息。為此,請將 addTarget(_:action:for:): 發送到要指定的每個 Target-Action 對的控制元件。
https://developer.apple.com/documentation/uikit/uicontrol/event
uj5u.com熱心網友回復:
我想到了。我們可以使用addAction代替addTarget. 需要 iOS 14 。
func addAction(_ action: UIAction, for controlEvents: UIControl.Event)可用于 UIControl 的所有子類。這意味著我們不再需要分散目標和@objc func我們的代碼。只需向您的控制元件添加一個 UIAction 即可。
class Button: UIButton {
init(type: String, action: UIAction) {
super.init(frame: .zero)
addAction(action, for: .touchUpInside)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/338360.html
