UILabel使用淡入淡出功能更新文本

时间:2019-11-17 04:54:11

标签: ios swift

我有一个UILabel,它每3秒更新一次。索引保存在用户默认设置中。下一个引号的更新没有问题,但是我无法像我第一次加载视图时那样将其变为fadeIn()。

       func changeLabelWithTimeInterval(){
    timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
}

@objc func updateCounting(){
    let defaults = UserDefaults.standard
    defaults.integer(forKey: "savedIndexKey")

    let currentIndex = defaults.integer(forKey: "savedIndexKey")
    var nextIndex = currentIndex+1

    nextIndex = quotes.indices.contains(nextIndex) ? nextIndex : 0
    defaults.set(nextIndex, forKey: "savedIndexKey")
    let savedInteger = defaults.integer(forKey: "savedIndexKey")
    saved = savedInteger


    quotesLabel.text = quotes[savedInteger]
    self.quotesLabel.fadeIn()



}
override func viewDidLoad() {
    changeLabelWithTimeInterval()
     self.quotesLabel.fadeIn()
    }

  extension UIView {
    func fadeIn(duration: TimeInterval = 5.0, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
        UIView.animate(withDuration: duration, delay: delay, options: .curveEaseIn, animations: {
            self.alpha = 1.0
        }, completion: completion)
    }

    func fadeOut(duration: TimeInterval = 3.0, delay: TimeInterval = 1.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in}) {
        UIView.animate(withDuration: duration, delay: delay, options: .curveEaseIn, animations: {
            self.alpha = 0.0
        }, completion: completion)
    }
}

1 个答案:

答案 0 :(得分:0)

我只是改用了这个扩展名。看起来很干净。

extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
    let animation = CATransition()
    animation.timingFunction = CAMediaTimingFunction(name:
        CAMediaTimingFunctionName.easeInEaseOut)
    animation.type = CATransitionType.fade
    animation.duration = duration
    layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}