1

I am creating a alert badge using UILabel using following code:

    [label setText:@"67"];
    UIFont * font = [UIFont systemFontOfSize:11];
    [label setFont:font];
    [label sizeToFit];

    [label setTextAlignment:NSTextAlignmentCenter];
    [label setBackgroundColor:[UIColor yellowColor]];
    [label setTextColor:[UIColor whiteColor]];
    label.layer.cornerRadius = label.frame.size.height/2;

Badge screenshot

Everything is fine but vertical alignment of text is not correct. Its more close to top edge. How can I align text in vertical center of UILabel?

I read about ascender and descender properties of UIFont, can I use them to align text in vertical center of UILabel.

dev gr
  • 2,409
  • 1
  • 21
  • 33

3 Answers3

2

You could use an attributed string instead of a plain NSString for the label's text (so use the attributedText property instead of text), and use the NSBaselineOffsetAttributeName attribute described here at Apple.

Cyrille
  • 25,014
  • 12
  • 67
  • 90
1

Another solution would be to subclass UILabel in order to add margins to the label, so you could define a custom "top margin" to compensate the baseline shift.

See this question to view the implementation details.

Community
  • 1
  • 1
Cyrille
  • 25,014
  • 12
  • 67
  • 90
-1

To vertically align the text of UILabel use -

myLabel.numberOfLines = 0;
[myLabel sizeToFit];

For detailed answer check This SO Answer

Community
  • 1
  • 1
Viper
  • 1,408
  • 9
  • 13