gpt4 book ai didi

函数有参数时 Swift Timer 错误

转载 作者:行者123 更新时间:2023-11-28 15:24:05 24 4
gpt4 key购买 nike

我正在尝试制作一个每隔一秒激活一次的函数,它将一个变量加 1 (texttimer) 并将一个字母添加到一个字符串 (typedStory) ,显示在标签上 (storyLabel)。

一切正常,直到我向函数添加一个参数 (finalStory)。现在我收到一个错误:

-[__NSCFTimer substringToIndex:]: unrecognized selector sent to instance

这是我的代码:

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,则不会执行我想要的操作。

有人知道解决办法吗?谢谢!

最佳答案

不,那行不通,action 方法将 timer 作为参数——错误消息告诉你的——你从 userInfo< 得到 finalStory/ 参数。

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
}

在 Playground 中试试这个

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

关于函数有参数时 Swift Timer 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com