[英]IOS Swift: Button Action in a separate class file
我只需要實現一個自定義類,該類在初始化時獲取按鈕的引用,然后在其中執行操作(Touch Up Inside)。
剛剛嘗試了以下方式,但收到一條異常消息:“無法識別的選擇器發送到實例0x7fbb48615ac0”
import UIKit
class CustomButton
{
var view: UIViewController
var btnTest: UIButton!
init(view: UIViewController, testBtn: UIButton)
{
self.view = view
self.btnTest = testBtn
// self.btnTest.addTarget(self, action: "btnMethod:", forControlEvents: UIControlEvents.TouchUpInside)
self.btnTest.addTarget(self, action: Selector("btnMethod:"), forControlEvents: UIControlEvents.TouchUpInside)
}
func btnMethod(sender: UIButton)
{
println("Click alright.....")
}
}
完整的異常消息如下
真的無法理解我在這里犯錯的地方。 非常感謝聽到我在做什么錯。 提前致謝!!!
編輯
以下是完整的工作解決方案
class CustomButton: NSObject
{
var view: UIViewController
var btnTest: UIButton!
init(view: UIViewController, testBtn: UIButton)
{
self.view = view
self.btnTest = testBtn
super.init()
self.btnTest.addTarget(self, action: Selector("btnMethod:"), forControlEvents: UIControlEvents.TouchUpInside)
}
deinit
{
println("De-Init happens...")
}
func btnMethod(sender: UIButton)
{
println("Click alright.....")
}
}
如果您更正確地看到自己的錯誤...由於未捕獲的異常而正在為應用程序加注[NSArray I按鈕方法:]。因此您的選擇器是錯誤的。
self.btnTest.addTarget(self, action:"btnMethod:", forControlEvents: UIControlEvents.TouchUpInside)
CustomButton類中的代碼很簡單,看起來很正確。 問題在於類實例(變量)被取消初始化,然后點擊按鈕,並試圖在未初始化的變量上調用選擇器。
您可以通過添加到CustomButton類來確認這一點:
deinit {
println("deinit")
}
如果您在點擊按鈕之前看到deinit發生,則表明點擊后它將崩潰。
解決方案是確保UIViewController中的CustomButton變量(customBtn)是該類的屬性,而不是局部變量。 這樣,只要您的UIViewController保持不變,CustomButton就會一直停留。
class PaymentViewController: UIViewController {
var customButton: CustomButton!
let button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// initialize self.button
// this instance will stick around for the life of the PaymentViewController
customButton = CustomButton(self, button)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.