如何在Swift中使用字符串类型删除时钟的运动时间数



我已经代码可以在我的应用程序中使用 timeLabel:UILabel显示时钟时间

那就是:

override func viewWillAppear(_ animated: Bool) {
    Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.currentTime), userInfo: nil, repeats: true)
}
func currentTime(){
    let date = Date()
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let second = calendar.component(.second, from: date)
    if second % 2 == 0{
        timeLabel.text = "(hour):(minutes)"
    }else {
        timeLabel.text = "(hour) (minutes)"
    }

但是,当小时和分钟之间的两个点消失时,它们会有点移动。如何解决?

用技巧😏可以解决。

通过在else条件下添加另一个具有相同背景颜色的标签,yup😉

对于 swift 3:

var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = self.view.backgroundColor
let attributedString = NSAttributedString(string: ":", attributes: attributes)
label.attributedText = attributedString

最新更新