简体   繁体   English

更改/循环标签中的文本

[英]Changing/looping text in label

I want to make my label change text every 5 seconds from rLabel.text = "\\(update) free trial" wait for another 5 second then change it rLabel.text = "upgrade now!" 我想让我的标签每5秒钟从rLabel.text = "\\(update) free trial"更改文本,再等待5秒钟,然后将其更改为rLabel.text = "upgrade now!" ~ on repeat. 〜重复。

rLabel.text = "\(update) free trial"
    if daysLeft <= 5 {
            let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
            timer.fire()
        }
    } else {
        rLabel.text = "\(update) free trial"
    }
@objc func update() {
    rLabel.text = "upgrade now!"
}

You can simply use a boolean to switch the text every 5 sec 您只需使用布尔值即可每5秒切换一次文本

override func viewDidLoad() {
     let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}

var isShowingText1 = false
@objc func updateText(){
    rLabel.text = isShowingText1 ? "Text 2" : "Text 1"
    isShowingText1 = !isShowingText1
}

You can keep track of current text by having index property. 您可以通过index属性跟踪当前文本。 Also you can use Timer with block closure and you can avoid having Obj-C-ish #selector 你也可以使用Timerblock关闭和你可以避免的OBJ-C-ISH #selector

var index = 0 {
    didSet {
        if index > 1 { index = 0 }
    }
}

var text: String {
    return ["\(update) free trial", "upgrade now!"][index]
}

func foo() {
    rLabel.text = text
    Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
        self.index += 1
        self.rLabel.text = self.text
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM