Automatically sets the uitableview (cell) line height based on the file content

Source: Internet
Author: User

In program development, a lot of data is dynamically obtained. Generally, the Row Height in uitableview is set to fixed. When the amount of text is large, the program will automatically hide unnecessary data, and add '... ', If the program needs to fully implement the data content, you need to change the Row Height in uitableview according to the content size.

Specific Practices:

For example, the cell has a contentlabel, which sets two attributes of this label:

Contentlabel. numberoflines = 0 // dynamically display the number of uilabel rows
Contentlabel. linebreakmode = uilinebreakmodewordwrap; // set the uilabel line feed mode.

Assume that datastring indicates the data content to be displayed, and contentlabelwidth indicates the actual width of the label,

CGSize size = [dataString sizeWithFont:font constrainedToSize:CGSizeMake(contentLabelWidth, 1500) 
lineBreakMode:UILineBreakModeWordWrap]; 

The value 1500 above is a virtual number, indicating the maximum number of texts that can be displayed. font is the font required for contentlabel.

In the heightforrowatindexpath method of uitableview, the Code is as follows:

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{         UIFont *font = [UIFont systemFontOfSize:14.0];         CGSize size = [dataString sizeWithFont:font constrainedToSize:CGSizeMake(contentLabelWidth, 1000)
Linebreakmode: uilinebreakmodewordwrap]; return size. height + 5; // 5 refers to the upper and lower message space, which can be adjusted freely}

The preceding 5 is also a virtual number used to set the line spacing or adjust the upper and lower message spaces.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.