Auto-sizing UITableViewCell in iOS 8

前端 未结 3 1209
[愿得一人]
[愿得一人] 2021-01-05 06:06

I have a UITableViewCell subclass which contains a multiline label, and I would like the cell to size itself dynamically based on the content of that label. I\'m aware that

3条回答
  •  别那么骄傲
    2021-01-05 06:45

    I just came across this issue.

    From numerous other Stackoverflow post they recommend:

    self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    

    That didn't work for me at first. I found that I also need to do:

    self.frame = CGRectMake(0, 0, self.frame.size.width, 50);
    

    My custom cell's init method looks like his:

    -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
        if(self)
        {
            [self initViews];
            [self initConstraints];
        }
    
        return self;
    }
    

    I put the code in my "initViews" method:

    -(void)initViews
    {
        ...
    
        // fixes an iOS 8 issue with UIViewEncapsulated height 44 bug
        self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        self.frame = CGRectMake(0, 0, self.frame.size.width, 50);
    }
    

    The problem went away and my cell looks correct too.

    Does this work for you?

提交回复
热议问题