我正在尝试创建一个每秒激活一次的函数,它向变量(texttimer
)添加1,并在字符串(typedStory
)上添加一个字母,该字母显示在标签(storyLabel
)。
一切正常,直到我向函数添加了一个参数(finalStory
)。现在我收到一个错误:
- [__ NSCFTimer substringToIndex:]:无法识别的选择器发送到实例
这是我的代码:
func textTypeWelcome(finalStory: NSString){
var newTimer2 = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(GameScene.textTypeWelcome), userInfo: finalStory, repeats: false)
texttimer += 1
typedStory = finalStory.substring(to: texttimer)
storyLabel.text = typedStory
}
如果删除参数并将userInfo
设置为nil,代码可以正常工作,但是不能做我想要的。
有人知道解决方案吗?谢谢!
答案 0 :(得分:1)
不,这不起作用,操作方法将计时器作为参数 - 错误消息告诉您 - 您从finalStory
参数获得userInfo
。< / p>
func textTypeWelcome(timer: Timer) {
let finalStory = timer.userInfo as! String
var newTimer2 = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(GameScene.textTypeWelcome), userInfo: finalStory, repeats: false)
texttimer += 1
typedStory = finalStory.substring(to: texttimer)
storyLabel.text = typedStory
}
在游乐场试试这个
class Foo : NSObject {
let string = "Hello World"
var counter = 1
var typedStory = ""
var timer = Timer()
override init() {
super.init()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
print("timer started")
}
func timerFired(timer : Timer) {
typedStory = string.substring(to: string.index(string.startIndex, offsetBy: counter))
print(typedStory)
if typedStory == string {
timer.invalidate()
print("timer stopped")
} else {
counter += 1
}
}
}
let foo = Foo()
你必须添加行
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
允许异步API