UILabel in UITableViewCell with auto layout has wrong height

前端 未结 6 976
孤独总比滥情好
孤独总比滥情好 2021-02-01 19:00

I have a UITableView with cells that have a fixed height of 100 points. The cells are created in a xib file that uses 3 constraints to pin a UILabel to

6条回答
  •  感情败类
    2021-02-01 19:36

    I'm using XCode 10 with iOS 12 and I still get autolayout problems with cells not being given the correct height when the table is first presented. Timothy Moose's answer didn't fix the problem for me, but based on his explanation I came up with a solution which does work for me.

    I subclass UITableViewController and override the viewDidLayoutSubviews message to check for width changes, and then force a table update if the width does change. This fixes the problem before the view is presented, which makes it look much nicer than my other efforts.

    First add a property to your custom UITableViewController subclass to track the previous width:

    @property (nonatomic) CGFloat previousWidth;
    

    Then override viewDidLayoutSubviews to check for width changes:

    - (void)viewDidLayoutSubviews {
        [super viewDidLayoutSubviews];
    
        CGFloat width = self.view.frame.size.width;
        if (self.previousWidth != width) {
            self.previousWidth = width;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }
    }
    

    This fixed issues with my table cells sometimes being given the wrong height initially.

提交回复
热议问题