繁体   English   中英

iOS Swift:单独的类文件中的按钮操作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM