ios - UILabel 更新文本并具有淡入功能

标签 ios swift

我有一个每 3 秒更新一次的 UILabel。索引保存在用户默认值中。下一个引用更新没有问题,但是我无法像第一次加载 View 时那样将其设置为 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)
    }
}

最佳答案

我只是使用了这个扩展。这样看起来干净多了。

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)
}
}

关于ios - UILabel 更新文本并具有淡入功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897608/

相关文章:

ios - 更新 UICollectionViewCell 中用户定义的 UIView 的内容

ios - 调用并添加到 UIScrollview 时未设置自定义 UIView 类的属性

ios - 如何确定 ScrollView 何时在正 x 方向和负 x 方向上滚动了至少一个屏幕宽度?

swift - SVProgressHUD 不工作

swift - 在 SpriteKit 中使用着色器绘制圆

swift - 如何快速按钮突出显示和突出显示颜色为红色

ios - 如何禁用特定单元格 ios 中的编辑模式?

ios - mergeChangesFromContextDidSaveNotification 消耗内存

iphone - 如何确定哪个事件称为imageMoved :withEvent:forControlEvents?

ios - CSS |网格自动列 : min-content | not working in IOS 10. 3.3