In iOS - How do I fit a UILabel to its text, without changing its position?

a 夏天 提交于 2019-12-12 09:36:19

问题


I'm calling sizeToFit on a UILabel which has right aligned text in it. It shrinks the height and width of the UILabeland fits the text to the top left of the UILabel.

Now...the position of the UILabel is incorrect. How can I make the UILabel stay in its original position (right aligned) or move it so it'll appear at its original position?

Once again - the problem is that the sizeToFit method is shrinking the width from the right side of the UILabel. It is treating the UILabel text as left aligned. But my text is right aligned. So, the right side border of the UILabel is where my text begins.


回答1:


You check the widths before & after, then move the center of the view right by the difference / 2.

By the way, I think the "box" (frame) is shrunk in both directions, keeping the center intact.




回答2:


@implementation UILabel (Additions)

- (void)sizeToFitWithAlignmentRight {
    CGRect beforeFrame = self.frame;
    [self sizeToFit];
    CGRect afterFrame = self.frame;
    self.frame = CGRectMake(beforeFrame.origin.x + beforeFrame.size.width - afterFrame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}

@end


来源:https://stackoverflow.com/questions/5549208/in-ios-how-do-i-fit-a-uilabel-to-its-text-without-changing-its-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!