我想从myTimer
函数中的startTimer()
函数访问backBtnPressed()
变量。基本上我想在我的myTimer.invalidate()
函数中添加此代码backBtnPressed()
。我怎样才能做到这一点?
func startTimer() {
var myTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(scrollToNextCell),
userInfo: nil,
repeats: true)
}
@IBAction func backBtnPressed(_ sender: UIButton) {
audioPlayer.stop()
}
答案 0 :(得分:1)
就目前而言,您无法访问myTimer
之外的startTimer()
变量,因为它超出了范围。为此,您需要将myTimer
声明为Class变量。他们,你需要初始化它,正如你所做的那样,你可以在Class中访问你想要的任何东西。另外不要忘记调用startTimer,否则它将返回nil。
看起来或多或少是这样的:
class YourViewController: ViewController {
var myTimer: Timer?
//some of your functions here
//...
override func viewDidLoad() {
super.viewDidLoad()
//...
startTimer()
}
func startTimer() {
myTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(yourFunction),
userInfo: nil,
repeats: true)
}
@IBAction func backBtnPressed(_ sender: UIButton) {
//do whatever you want
myTimer.invalidate()
}
}
答案 1 :(得分:0)
简单地让你的计时器成为一个属性:
class MyClass {
var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextCell), userInfo: nil, repeats: true)
}
@IBAction func backBtnPressed(_ sender: UIButton) {
audioPlayer.stop()
timer.//do something with timer
}
}