【问题标题】:iOS Prevent UILabel text 'shaking' when numbers changeiOS防止UILabel文本在数字变化时“摇晃”
【发布时间】:2017-03-21 00:16:00
【问题描述】:

我有一个自定义视图,在这个视图之上我有一个 UILabel。放置在视图中间的标签。标签显示当前速度。标签的整数部分的文本大小大于小数部分的文本大小。我在标签文本的两个部分都使用monospacedDigitFont 以防止数字变化时文本晃动/移动,NSMutableAttributedString 能够设置标签文本的不同大小。显然它不起作用。

自定义视图:

代码片段:

func updateSpeed(){
        dummySpeed += 4.0

        speedometerView.currentSpeed = speedometerView.setSmoothSpeed(SpdAv: dummySpeed)

        let myString = String(Float(round(speedometerView.currentSpeed * 10) / 10))
        let attrString = NSMutableAttributedString(string: myString as String)
        attrString.addAttribute(NSFontAttributeName, value: currentSpeedLabel.font.monospacedDigitFont, range: NSMakeRange(0, 1))
        attrString.addAttribute(NSFontAttributeName, value: currentSpeedLabel.font.monospacedDigitFont.withSize(20), range: NSMakeRange(2, 1))

        currentSpeedLabel.attributedText = attrString
    }

我做错了什么?

【问题讨论】:

    标签: ios swift3 uilabel


    【解决方案1】:

    如果您是 iOS 新手,这并不容易。 这是一个解决方案:

    @IBOutlet weak var currentSpeedLabel: UILabel! {
            didSet{
                currentSpeedLabel.font = UIFont.monospacedDigitSystemFont(
                    ofSize: UIFont.systemFontSize * 2,
                    weight: UIFontWeightRegular)
            }
        }
    
    func updateSpeed(){
            dummySpeed += 4.0
    
            speedometerView.currentSpeed = speedometerView.setSmoothSpeed(SpdAv: dummySpeed)
    
            let myString = String(Float(round(speedometerView.currentSpeed * 10) / 10))
            let attrString = NSMutableAttributedString(string: myString as String)
            attrString.addAttribute(NSFontAttributeName, value: UIFont.monospacedDigitSystemFont(
                ofSize: UIFont.systemFontSize,
                weight: UIFontWeightRegular), range: NSMakeRange(attrString.length - 1, 1))
    
            currentSpeedLabel.attributedText = attrString
        }
    

    【讨论】:

      猜你喜欢
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多