簡體   English   中英

當數字更改時,iOS防止UILabel文本“晃動”

[英]iOS Prevent UILabel text 'shaking' when numbers change

我有一個自定義視圖,在此視圖之上,我還有一個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的新手,這並不容易。 這是一個解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM