简体   繁体   中英

Autosize UILabels in custom style UITableViewCell

I've got a UITableView with two cell prototypes. One (the first one in the screenshot above) you might recognise as the subtitle style standard cell. The second one is custom , with an extra text field.

When I run the app, the labels using the first template size their width nicely depending on the size of the text in them, whereas the one using custom template doesn't scale, effectively clipping the text after three characters.

Is there a way to configure the custom template in XCode Storyboard designer to size the label like the built-in subtitle cell template does?

单元格模板

Set Constraints as shown in figure

在此处输入图片说明

The truncated label in image (T..) is TextField.

Set Row height to minimum size for the Cell as 155.

Try this:

You can change the size of the label with respect to the text entered in the textfield

-(CGSize)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode      
{

NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = lineBreakMode;

NSDictionary * attributes = @{NSFontAttributeName:font,
                              NSParagraphStyleAttributeName:paragraphStyle
                              };
CGRect textRect = [text boundingRectWithSize:size
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attributes
                                     context:nil];
return textRect.size;
}

Calling the Method:

CGSize size =[self frameForText:body sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:NSLineBreakByWordWrapping];

Thanks

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