UITableViewCell, UITextView with dynamic height

前端 未结 3 1281
孤城傲影
孤城傲影 2020-12-02 16:04

I need to make a UITableViewCell that holds alot of text. I know I can add a UITextView to my cell, but each entry will not have the same amount of

相关标签:
3条回答
  • 2020-12-02 16:13

    It's rather complicated stuff, as it involves things like the contentInset of he text view you will have to take into account when calculating the texts size. I've written up my learnings and solution for calculating the UITableViewCell height based on an inner UITextView on my blog. The post contains the code that works for universal apps, both table view styles and autorotation.

    0 讨论(0)
  • 2020-12-02 16:16

    The solution is quite simple and should work since iOS 7. Make sure that the Scrolling Enabled option is turned off for the UITextView inside the UITableViewCell in the StoryBoard.

    Then in your UITableViewController's viewDidLoad() set the tableView.rowHeight = UITableViewAutomaticDimension and tableView.estimatedRowHeight > 0 such as:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44.0
    }
    

    That's it. UITableViewCell's height will be automatically adjusted based on the inner UITextView's height.

    0 讨论(0)
  • 2020-12-02 16:29

    Use UILabel for your cell text. You can then use sizeWithFont:constrainedToSize: to calculate the height of that UILabel within each cell. For example:

    #define PADDING 10.0f
    
    - (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *text = [self.items objectAtIndex:indexPath.row];
        CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];
    
        return textSize.height + PADDING * 3;
    }
    
    0 讨论(0)
提交回复
热议问题