[英]Ios swift replace selector by function
我只想在按鈕點擊上寫一兩行代碼
print("Button Clicked")
為此我不想創建一個單獨的功能,並通過選擇器調用
action: #selector(BtnKlkFnc(_:))
我想簡化一下
action: { action in print("Button Clicked")}
我也試過了
#selector({print("Button Clicked")})
任何人都可以幫我簡化這一點
我是stackoverflow的新手,還沒有足夠的聲譽,所以請投票支持我的問題,所以我可以投票給你的ans
簡短回答:你做不到。 Button動作是Cocoa / Cocoa touch內置的目標/動作機制的一部分。 它基於選擇器,您必須創建一個命名方法並使用它的選擇器。 您不能使用Swift閉包作為按鈕操作。
請注意,可以創建具有閉包屬性的UIButton的自定義子類,並在點擊按鈕時調用該閉包。 你要做的是讓按鈕的init方法自己設置為touchUpInside事件的目標,並調用按鈕的方法,然后調用你的閉包(在確保closure屬性不是nil之后)。
請注意,創建UIButton
的自定義子類非常簡單,它將自身設置為按下按鈕的目標並保持閉包。
這是一個示例實現:
class ClosureButton: UIButton {
var buttonClosure: ((UIButton) -> Void)?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addTarget(self, action: #selector(handleTap(_:)), for: .touchUpInside)
}
@objc func handleTap(_ sender: UIButton) {
if let buttonClosure = buttonClosure {
buttonClosure(sender)
} else {
print("No button closure defined")
return
}
}
}
並在您的視圖控制器中:
override func viewDidLoad() {
super.viewDidLoad()
button.buttonClosure = { _ in
print("You tapped the button")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.