UILabel sizeToFit only works with AutoLayout turned off

非 Y 不嫁゛ 提交于 2019-12-10 21:19:19

问题


So I am making an app using iOS 6 and was wondering why my code that used to work great on iOS 5 does not work anymore. I have a cell with dynamic UILabel that gets adjusted based on the text that it carries.

This is with autolayout turned on:

This is with autolayout turned off:

Here is my code:

- (CGFloat)heightForText:(NSString *)bodyText
{

#define FONT_SIZE 13.0f
#define CELL_CONTENT_WIDTH 280.0f
#define CELL_CONTENT_MARGIN 5.0f

    CGSize constraintSize = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize labelSize = [bodyText sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat height = MAX(labelSize.height, 36.0f);
    //   NSLog(@"height=%f", height);
    return height + (CELL_CONTENT_MARGIN * 2);

}



- (CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSInteger section = [indexPath section];

    switch (section) {


        case 0:
            if ([self.text.text length]!=0)
            {
                return [self heightForText:self.text.text];
            }
            else if ([self.link.text length]!=0)
            {

               return 60.0f;

            }
}

回答1:


The code you've shown is fine, the problem is most likely within the constraints you have on the label within your cell (which you don't show).

Your label needs to have constraints to make it a fixed distance from each edge of its superview. This may already be the case - if so, the problem is now that the label doesn't know how to wrap its lines - you need to also set the preferredMaxLayoutWidth on the label.

I have found that tools such as DCIntrospect are really helpful when debugging Autolayout issues. For example, in this situation, its hard to tell if this is a label of the right size that is not wrapping text, or if the label is not tall enough to show your content properly.



来源:https://stackoverflow.com/questions/14922803/uilabel-sizetofit-only-works-with-autolayout-turned-off

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