UITableViewCell如何自动拉伸

1.现在xib中设置好布局

  1. 将需要的拉伸的控件拖到.m文件中,设置preferredMaxLayoutWidth属性

 #import "TMContentCell.h"

@interface TMContentCell()
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation TMContentCell

-(instancetype)init {
if (self = [super init]) {
self = [[NSBundle mainBundle] loadNibNamed:@"TMContentCell" owner:nil options:nil].firstObject;
}
return self;
}

-(void)awakeFromNib {
// Initialization code
self.label.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 16;
// [self.label setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
}

-(void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}

@end

之后再heightForRowAtIndexPath 中设置指定cell的systemLayoutSizeFittingSize属性


-(void)createUI {
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

CGFloat height = [[[TMContentCell alloc] init].contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 0.5;

return height;

}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[TMContentCell alloc] init];

return cell;

}

demo

你可能感兴趣的:(UITableViewCell如何自动拉伸)