美文网首页
10.7 Masonry-cell高度自适应

10.7 Masonry-cell高度自适应

作者: 草根小强 | 来源:发表于2019-04-26 17:30 被阅读0次
#import "ViewController.h"
#import "MyCell.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableV;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableV = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    
    //让cell根据label的大小改变
    self.tableV.rowHeight = UITableViewAutomaticDimension;
    //cell虚拟高度
    self.tableV.estimatedRowHeight = 44.0f;
    
    [self.tableV registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellReuseIdentifier:@"id"];
    [self.view addSubview:self.tableV];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 
    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"id" forIndexPath:indexPath];
    cell.label1.text = [self randStr];
    cell.label2.text = [self randStr];
    [cell addConstraintForLabel];
    return cell;
}

- (NSString *)randStr{
    int num = arc4random()%50+5;
    NSMutableString *str = [[NSMutableString alloc]init];
    for (int i = 0; i < num; i++) {
        [str appendString:@"随机数据.."];
    }
    return str;
}

@end

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell


@property (strong, nonatomic) UILabel *label1;

@property (strong, nonatomic) UILabel *label2;

- (void)addConstraintForLabel;


@end
#import "MyCell.h"
#import "Masonry.h"

@implementation MyCell

- (void)awakeFromNib {
    self.label1 = [[UILabel alloc]init];
    self.label2 = [[UILabel alloc]init];
    self.label2.numberOfLines = 0;
    self.label1.numberOfLines = 0;
    
    self.label1.textColor = [UIColor redColor];
    self.label2.textColor = [UIColor greenColor];
    [self.contentView addSubview:self.label1];
    [self.contentView addSubview:self.label2];
    
}
- (void)addConstraintForLabel{
    
    [self.label1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self.contentView).offset(10);
        make.right.mas_equalTo(self.contentView).offset(-10);
        
    }];
    
    [self.label2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView).offset(10);
        make.right.bottom.mas_equalTo(self.contentView).offset(-10);
        make.top.mas_equalTo(self.label1.mas_bottom).offset(10);
    }];

}

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

    // Configure the view for the selected state
}

@end
Masonry-cell高度自适应.png

相关文章

网友评论

      本文标题:10.7 Masonry-cell高度自适应

      本文链接:https://www.haomeiwen.com/subject/wwpqnqtx.html