[英]Is there a different option than addTarget on a UIButton
所以我知道您可以在按鈕上使用addTarget,如下所示:
import UIKit
class ViewController: UIViewController {
func calledMethod(_ sender: UIButton!) {
print("Clicked")
}
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
btn.backgroundColor = UIColor.darkGray
btn.addTarget(self, action: #selector(self.calledMethod(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
}
}
這絕對可以正常工作,但我只是想知道是否還有另一種方法可以檢測何時單擊某項,並在發生這種情況時運行一些代碼。
您可以在情節提要中添加按鈕並為其動作創建出口。
@IBAction func buttonAction(_ sender: UIButton) {
//implement your code here
}
您也可以看看RxSwift / RxCocoa或類似的東西。 所有更改和操作都會自動添加,您可以決定是否要觀察它們。
代碼看起來像這樣:
let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
btn.backgroundColor = UIColor.darkGray
btn
.rx
.tap
.subscribe(onNext: {
print("Clicked")
}).disposed(by: disposeBag)
view.addSubview(btn)
按鈕是UIControl
的子類。 UIControl
設計為使用目標/動作來指定發生指定動作時要運行的代碼。 如果您不想使用該機制,則必須創建一個等效項。
你可以附上敲擊手勢識別其他一些對象,並設置它的userInteractionEnabled標志設置為true,但手勢識別也使用目標/行動模式。
我的建議是“不要擔心,要學會愛按鈕”。 只是學習使用目標/動作。
另一種可能性:創建UIButton
的自定義子類,該子類在初始化時將其自身設置為自己的目標(特別是init(coder:)
和init(frame:)
,這是您需要為視圖對象實現的2種init方法。)將包含一個閉包數組,如果點擊該按鈕,閉包數組的動作方法將執行該閉包。 它將具有添加或刪除閉包的方法。 然后,您需要在視圖控制器中放置一個這樣的按鈕,然后調用該方法以添加所需的閉包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.