swift - xcode swift 4 数字增加动画?

标签 swift

我正在尝试为 swift 4 中的 UILabel 数量增加设置动画,我对这种语言还是新手,我想做的是:

for index in 1...500 {
   self.lbl_counter.text = "\(index)"
}

值始终为 500 。

我也尝试过这个

 for index in 1...500 {
DispatchQueue.main.async{
       self.lbl_counter.text = "\(index)"
}
    }

what did i miss here to make it animate increasing the numbers ?

最佳答案

尝试以下代码

import UIKit

class ViewController: UIViewController
{
    /// Label
    private var customLabel : UILabel?

    /// MAximum Count to which label will be Updated
    private var maxCount : Int?
    /// Count which is currently displayed in Label
    private var currentCount : Int?
    /// Timer To animate label text
    private var updateTimer : Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        customLabel = UILabel()
        customLabel?.textColor = .black

        /// Add label to View
        addConstraints()

        /// Start Timer
        DispatchQueue.main.async {
            self.maxCount = 100
            self.currentCount = 0
            self.updateTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateLabel), userInfo: nil, repeats: true)
        }
    }

    @objc func updateLabel() {
        self.customLabel?.text = String(currentCount!)
        currentCount! += 1
        if currentCount! > maxCount! {
            /// Release All Values
            self.updateTimer?.invalidate()
            self.updateTimer = nil
            self.maxCount = nil
            self.currentCount = nil
        }
    }

    func addConstraints(){
        /// Add Required Constraints
        self.view.addSubview(customLabel!)
        customLabel?.translatesAutoresizingMaskIntoConstraints = false
        customLabel?.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 50).isActive = true
        customLabel?.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50).isActive = true
        customLabel?.heightAnchor.constraint(equalToConstant: 50).isActive = true
        customLabel?.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
    }
}

enter image description here

关于swift - xcode swift 4 数字增加动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50463885/

相关文章:

ios - ARKit - SCNNode 连续运动

ios - UICollectionViewCell 复选标记返回 nil

swift - 从午睡响应中获取 HTTPURLResponse

ios - 在特定条件下切换约束

arrays - 用字典应用 Array.map

ios - 用项目符号格式化 UILabel?

ios - CALAYER 应用背景颜色加图案图像

swift - 我可以向 Stormpath 中的其他用户显示用户数据吗?

performance - Swift 处理数字真的很慢吗?

ios - 'AppDelegate' 没有名为 'navController' 的成员