AutoLayout uitableviewcell in landscape and on iPad calculating height based on portrait iPhone

后端 未结 2 375
予麋鹿
予麋鹿 2021-01-01 03:54

I\'m learning / experimenting with autolayout and UITableViewCell\'s. I asked another question a few days ago to which I answered my own question, I\'m still us

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 03:59

    I'm still trying to figure out how to make systemLayoutSizeFittingSize work correctly, especially when I have multiple multi-line labels. I have one test app that seems to work, but why it works, is still a bit of a mystery. So, I have a subclassed label that has the same code that you're using,

    - (void)layoutSubviews {
        self.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
        [super layoutSubviews];
    }
    

    In heightForRowAtIndexPath;, I'm also setting the preferredMaxWidth (using some hard coded numbers based on the constraints). If I remove either of these calls to preferredMaxWidth, it doesn't work properly. Removing the ones in heightForRowAtIndexPath gives me extra space in my labels, similar to what you're seeing.

    - (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
        static RDCell *sizingCell;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sizingCell = (RDCell*)[tableView dequeueReusableCellWithIdentifier: @"Cell"];
        });
        sizingCell.label.text = self.theData[indexPath.row];
        sizingCell.bottomLabel.text = self.theData2[indexPath.row];
        sizingCell.label.preferredMaxLayoutWidth = tableView.bounds.size.width - 40; // the 40 comes from the 20 point spacing constraint to each side of the cell setup in the storyboard
        sizingCell.bottomLabel.preferredMaxLayoutWidth = tableView.bounds.size.width - 40;
        return [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height + 2; // the calculation seems to be low by 1 (per label), so add 2 for my 2 labels
    }
    

    In this test project, my custom cell has two labels arranged over top of each other. I know this isn't an ideal solution, I'm still testing to see why this works, and why it doesn't with just one of the uses of preferredMaxWidth. In preliminary tests, it looks like it might be a timing issue, as to when the various methods are called at startup and when they're called on rotation.

提交回复
热议问题