sizeToFit is functioning oddly

為{幸葍}努か 提交于 2019-12-10 10:07:37

问题


I have a segment of code that gets executed everytime a backend database change occurs. Essentially I have a label inside of a parent view. The label gets updated by one of many status messages each one on a different line ended by a new line (\n). Each status message needs to be on one line only and not go over.

The problem I am having is that everything works fine when the View first reloads. However when I am on the screen and a change occurs in background, once in a while a status message displays on multiple lines. While sizeToFit does a great job of making the label as high as the parent containing view, it does so poorly in terms of width. That is it will break up text on multiple lines as opposed to looking at the line breaks only.

What can I do?

self.messageLabel.text = message; //lets get the status message.
        [self.messageLabel sizeToFit];
        [self.messageLabel setNeedsDisplay];
        CGRect frame = [self.messageView frame];
        frame.size.height = self.messageLabel.bounds.size.height;
        self.messageView.frame = frame;
        self.messageLabel.center = CGPointMake(CGRectGetMidX(self.messageView.bounds), CGRectGetMidY(self.messageView.bounds)-(self.messageView.cornerRadius/4));
        self.messageLabel.backgroundColor = [UIColor orangeColor];
        [self.messageView setNeedsDisplay];

回答1:


In order to determine the size that your label will need to be, you need to look into the NSString size methods. There's a number of them that can tell you the size a string will be given a font, and various constraints.

For example [@"string" sizeWithFont: forWidth: lineBreakMode:]; will return a CGSize that you can then use to size your label appropriately.

As an aside, I find the UILabel does not handle strings with multiple lines well. You may be better off writing your own subview of UIView that can handle multiple lines of text, each with its own label.




回答2:


It seems to happen each time the frame is resized after the initial operation. Presumably the frame's current size is used when deciding the new size in -sizeToFit. The workaround I'm using is to set the view's frame to a pre-defined size before each call to sizeToFit, e.g:

myLabel.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.width.height);
[myLabel sizeToFit];


来源:https://stackoverflow.com/questions/8556880/sizetofit-is-functioning-oddly

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