How to adjust baseline shift for UiLabel?

My application uses its own font to display information for the entire application.

But there are some problems with their baseline as in the image below:

enter image description here

I need to fix "X 4" so that it is centered in the vertical red box.

How can I fix this?

+3


source to share


2 answers


You can create UILabel

and size it the same as red. And then set its text alignment to center:

youLabel.textAlignment = NSTextAlignment.Center

      



Another not very good option is to make UIButton

the same size as the red box and set it UserInteractionEnabled

to No

. This will keep your text centered horizontally and vertically. You can also set its setContentVerticalAlignment

property

+1


source


Set the attributed string with the corrected baseline offset as shown in Swift:

let sttrStr = NSAttributedString.init(string: "your text",
                                      attributes:[NSAttributedStringKey.baselineOffset: -10])
textLabel.attributedText = attrStr

      

or so in ObjC:



NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"your string"
                              attributes:@{ NSBaselineOffsetAttributeName : @-10 }];
textLabel.attributedText = attrStr;

      

Per SO answer here

0


source







All Articles