斯威夫特:让按钮工作

时间:2015-10-22 09:26:18

标签: ios swift uibutton viewdidload

我在viewDidLoad()功能中创建了两个按钮:

    buttonZ.frame = CGRectMake(0, 20, 100, 50)
    buttonZ.backgroundColor = UIColor.greenColor()
    buttonZ.setTitle("Zurück", forState: UIControlState.Normal)
    buttonZ.addTarget(self, action: "buttonZAction:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(buttonZ)

    buttonV.frame = CGRectMake(screenBreite - 100, 20, 100, 50)
    buttonV.backgroundColor = UIColor.greenColor()
    buttonV.setTitle("Vorwärts", forState: UIControlState.Normal)
    buttonV.addTarget(self, action: "buttonVAction:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(buttonV)

viewDidLoad()之外,我实施了两项功能buttonZAction()buttonVAction()

    func buttonZAction(){
    if(level - 1 >= 1){
        level = level - 1
        spielfeldChooser()
    }
}

func buttonVAction(){
    if(level + 1 <= maxLevel){
        level = level + 1
        spielfeldChooser()
    }
}

当我按下这些按钮时会出现问题。某处出现异常,我没有抓到(我只是包含了错误的主要部分)。

`***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [Pushy_2_0.ViewController buttonVAction:]:无法识别的选择器发送到实例0x15db5410'

我希望你能帮助我。

3 个答案:

答案 0 :(得分:1)

您有"buttonZAction:"这意味着您的选择器应该接收参数。如果你没有通过它们改变这些行:

buttonZ.addTarget(self, action: "buttonZAction:", forControlEvents: UIControlEvents.TouchUpInside)
buttonV.addTarget(self, action: "buttonVAction:", forControlEvents: UIControlEvents.TouchUpInside)

要:

buttonZ.addTarget(self, action: "buttonZAction", forControlEvents: UIControlEvents.TouchUpInside)
buttonV.addTarget(self, action: "buttonVAction", forControlEvents: UIControlEvents.TouchUpInside)

答案 1 :(得分:0)

你的选择器有一个参数。但是你没有在函数 buttonZAction 中声明这个参数 像这样

func buttonZAction(sender: UIButton!){
    if(level - 1 >= 1){
        level = level - 1
        spielfeldChooser()
    }
}

func buttonVAction(sender: UIButton!){
if(level + 1 <= maxLevel){
    level = level + 1
    spielfeldChooser()
}
}

答案 2 :(得分:0)

您在String的末尾添加了“:”,表示操作方法的名称,后者不带任何输入参数。不要误会,最好像这样使用Selector类:

buttonV.addTarget (self, Action: Selector (buttonVAction ()), forControlEvents: UIControlEvents.TouchUpInside)