Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel with "+" text not centered vertically

enter image description here

self.iconLabel.frame = self.contentView.frame;

self.iconLabel.font = [UIFont systemFontOfSize:100.0];
self.iconLabel.text = @"+";
self.iconLabel.textColor = [UIColor blackColor];
self.iconLabel.textAlignment = NSTextAlignmentCenter;

So the UILabel's frame is the same size as its container view, self.contentView

I need the "+" to be centered vertically also, I want it in the center.

How can I achieve this?

My only notion is to shift the iconLabel.frame up.

EDIT: Changed from self.iconImageView to self.contentView which is a UIView. The UILabel is layered above the self.iconImageView which is a UIImageView.

EDIT 2: Tried implementing kshitij godara's code, the result is:

enter image description here

I altered the code slightly:

CGSize constraint = CGSizeMake(self.contentView.frame.size.width, self.contentView.frame.size.height);

NSString *str = @"+";

UIFont *myFont = [UIFont systemFontOfSize:100.0];

CGSize stringSize = [str sizeWithFont:myFont constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

self.iconLabel.frame = CGRectMake(0, 0, stringSize.width, stringSize.height);
self.iconLabel.font = myFont;
self.iconLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.iconLabel.numberOfLines = 0;
[self.iconLabel sizeToFit];
self.iconLabel.text = str;

EDIT 3:

the frame is quite large:

enter image description here

like image 626
Padin215 Avatar asked Feb 16 '26 09:02

Padin215


1 Answers

This is probably a problem of the font itself. Each font has defined it shapes, behavior, typesetting etc. The font seems to be positioning character "+" of the visual vertical center. You can test it on any other string containing letter "+", "dog+Cat" for example. The "+" letter will probably be drawn near bottom as it is on your image.

From my point of view, you have 2 options:

  • Use icon image instead for the "+" sign. This will be simplest and the best working solution
  • Use custom font edited to visually look exactly like you need (letter "+" totally centered in its typeset). This one would probably be very painfull and time-consuming option

Edit: Regarding 2nd option: I have already done such an procedure to fix some misaligned fonts following this tutorial. However it still just fixes the whole font, not on a single character basis

like image 76
Lukas Kukacka Avatar answered Feb 21 '26 13:02

Lukas Kukacka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!