以NSException类型的未捕获异常终止
这是我的代码,当我按下按钮时出现错误。
var startButton : UIButton!
var theTime = 0;
var countDownText = "hello"
var countDownTimer = NSTimer
startButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
startButton.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height/3)
startButton.setTitle("\(countDownText)", forState: UIControlState.Normal)
startButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
startButton.addTarget(self, action: Selector("countDownFunc"), forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(startButton)
func countDownFunc() {
countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc2:"), userInfo: nil, repeats: true)
}
func countDownFunc2(){
theTime++
countDownText = "HELLOOOOOOOOO"
}
print(theTime)
我不知道如何修复此错误:( 任何帮助将不胜感激!!
答案 0 :(得分:1)
看起来您在错误的范围内定义了该方法。你似乎有像
这样的东西func mySpecialFunc() {
...
startButton.addTarget(self, action: Selector("countDownFunc"), forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(startButton)
func countDownFunc() {
countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc2:"), userInfo: nil, repeats: true)
}
func countDownFunc2(){
theTime++
countDownText = "HELLOOOOOOOOO"
}
print(theTime)
}
这意味着countDownFunc
和countDownFunc2
功能仅在mySpecialFunc
范围内定义并可用。您正在操作的对象/类对它一无所知,因此您的计时器和操作选择器都会失败。你要做的就是将这两种方法移出mySpecialFunc
的主体:
func mySpecialFunc() {
...
startButton.addTarget(self, action: Selector("countDownFunc"), forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(startButton)
}
func countDownFunc() {
countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc2"), userInfo: nil, repeats: true)
}
func countDownFunc2(){
theTime++
countDownText = "HELLOOOOOOOOO"
}
答案 1 :(得分:0)
嘿看this。
myButton.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)
let timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval: 1, target: self, selector: "test", userInfo: nil, repeats: false)
// cit
他没有使用selector: Selector("method name")
,他使用selector: "method name"