防止在使用Timer快速更改标签时UIButton标签不闪烁

时间:2018-08-16 05:06:43

标签: ios swift uibutton

我正在尝试将计数器值添加到UIButton标签中,如下所示:

TEST.txt

并更改UIButton标签功能

override func viewDidLoad() {
    super.viewDidLoad()
    let counterAttribute = Settings.changeButtonStyle(fullString: String(format: "Continue in %d secs", self.otpTimer) as NSString, boldPartsOfString: "Continue", changeFontString: "\(self.otpTimer)")
    self.continueButton.setAttributedTitle(counterAttribute, for: .normal)
    Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
}

func updateTimer() {
    self.otpTimer = self.otpTimer - 1
    let counterAttribute = Settings.changeButtonStyle(fullString: String(format: "Continue in %d secs", self.otpTimer) as NSString, boldPartsOfString: "Continue", changeFontString: "\(self.otpTimer)")
    self.continueButton.setAttributedTitle(counterAttribute, for: .normal)
}

问题是每当更改计时器时,UIButton标签闪烁。这就是为什么我想知道如何通过更改上面的代码来使UIButton标签不闪烁。谢谢。

2 个答案:

答案 0 :(得分:1)

我找到了一种解决方法,我们还需要添加UIView.performWithoutAnimation以防止不刷新UIView。

UIView.setAnimationsEnabled(false)
myTimer = myTimer - 1
UIView.performWithoutAnimation {
    /* Change UIButton Label */
    UIView.setAnimationsEnabled(true)
}

答案 1 :(得分:0)

在这两个调用之间添加标题更新:

UIView.setAnimationsEnabled(false)
/// update button title
UIView.setAnimationsEnabled(true)