简体   繁体   中英

How to center align a UILabel on top of an UIImageView

I have an UIImageView that has a UILabel on top of it. This UILabel has a text that shows a number to the user of how many people like his content ( kinda like the Facebook likes or comments ), Both the UIImageView and the UILabel are small in size so the UI needs to be just perfect. Right now if the UILabel shows a 2 digits number it still shows up aligned properly but when I get into the 3 digits it kinds skews off, how can I make sure that I can always align it to the UIImageView via code?

Similar to Scott's answer, but with the code that the poster requested

//assume that UIImageView (imageView) and UILabel (label) are already defined
label.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y - label.frame.size.height, imageView.frame.size.width, label.frame.size.height);
label.textAlignment = UITextAlignmentCenter;

Note: You'll also need to ensure that the struts and autoresize masks of the UILabel appropriately match that of the UIImageView to ensure this looks appropriately on screens of different sizes and different orientations.

屏幕快照会很好,但是您始终可以尝试使标签与图像的宽度相同,然后将标签的文本居中。

Try this:

UILabel *label = [[UILabel alloc] initWithFrame:imageView.frame];
label.textAlignment = NSTextAlignmentCenter;

This might work as UITextAlignmentCenter is deprecated in iOS 6 and above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM