【问题标题】:@IBAction crashes app in Swift@IBAction 在 Swift 中使应用程序崩溃
【发布时间】:2014-06-15 06:56:56
【问题描述】:

我有按钮和方法

 switchViewButton = UIButton.buttonWithType(.System) as? UIButton
    switchViewButton!.frame = CGRectMake(15, 25, 50, 50)
    switchViewButton!.setTitle("sss", forState: .Normal)
    switchViewButton!.addTarget(self, action: "switchViewFunc", forControlEvents: .TouchUpInside)
    switchViewButton!.backgroundColor = UIColor.redColor()
    switchViewButton!.layer.cornerRadius = 25
    topView.addSubview(switchViewButton)


@IBAction func switchViewFunc(sender : AnyObject){
     println("Button was clicked", sender)}

此方法使应用程序崩溃,原因是“无法识别的选择器已发送到实例”

我有另一个按钮和方法,就像这样,它工作得很好。如果我删除 (sender : AnyObject) 它可以工作。我不明白怎么回事

【问题讨论】:

  • 为什么在手动将 IBAction 添加为目标时使用它? IBAction 专门用于挂钩 IB 中的东西。您可以将其定义为常规函数。

标签: ios swift


【解决方案1】:

这样添加动作(注意“:”

switchViewButton!.addTarget(self, action: "switchViewFunc:", forControlEvents: .TouchUpInside)

【讨论】:

  • 这很奇怪,我还有另一个带有代码 lockButton!.addTarget(self, action: "lockandUnlock", forControlEvents: .TouchUpInside) 的按钮,它不是崩溃的应用程序
  • 如果你在switchViewFunc中有参数那么你需要添加:
  • @IvanR 那么该函数没有任何参数。您需要了解方法签名的工作原理。看到这个stackoverflow.com/questions/297680/…
【解决方案2】:
@IBAction func switchViewFunc(sender : AnyObject){
     println("Button was clicked", sender)} - ?????

试试这个:

func switchViewFunc(sender : UIButton!){
     println("Button was clicked", sender)
}

【讨论】:

    【解决方案3】:

    不需要@IBAction 和参数。

    func switchViewFunc(){
        println("Button was clicked", sender)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多