How do I disable sizeToFit on UILabel?

Asked 2 years ago, Updated 2 years ago, 79 views

I'm making a clock application. (It's a digital number, not a hand.) I use UILabel to display time, but whenever the number of time changes, the size of the UILabel is resized and the font of the displayed number moves slightly from side to side.I want to feel natural like a watch app such as iPhone, but what should I do? I wonder if it's because of sizeToFit, but I just placed the UILabel on the storyboard, but I didn't give instructions by code.It may be solved by using an equal width font, but is it possible to use such a font? Thank you in advance.

uikit uilabel

2022-09-30 21:17

1 Answers

I have doubts about whether the size of the UILabel is resized, but it is consistent with my experience that the font of the numbers displayed also moves slightly from side to side.The reason for this is that each number has a different width because it is not an equal width, as you can guess from the fact that it may be solved by using an equal width font.
Therefore, using an equal width font is the only and best solution.However, all characters need to be equal in width, and all characters need not be equal in width.
If you want to use system fonts without specifying any particular font, use the class method class func monospacedDigitSystemFontOfSize(_fontSize:CGFloat, weight:CGFloat) ->UIFont for the class.

In the ViewController class

override func viewDidLoad(){
    super.viewDidLoad()

    // digitLabel is a label that displays the time.
    digitLabel.font=UIFont.monospacedDigitSystemFontOfSize (55.0, weight:UIFontWeightBlack)
}

55.0 specifies the font size.Specify as appropriate, where UIFontWeightBlack is a constant (constant) font weight.UIFontDescriptor has a list of all weights in the class reference.

iOS simulator

Display results by the iOS simulator.The top is just a system font.Below is the monospacedDigitSystemFont.You can see that the width of the number "1" is different.


2022-09-30 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.