autolayout 高度自适应

https://lvwenhan.com/ios/449.html

 

#import "ViewController.h"
#import "MyTableViewCell.h"
static NSString *cellIdentifier = @"mycell";

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *listArr;
@property (strong, nonatomic) MyTableViewCell *cell;
@end

@implementation ViewController
@synthesize listArr;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellIdentifier];
    self.tableView.estimatedRowHeight = 44;//很重要保障滑动流畅性
    self.cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    self.listArr = @[@"Do any additional setup after loading the view, typically from a nib.",
                     @"test",
                     @"UITableViewCell 高度自适应一直是我们做动态Cell高度时遇到的最烦躁的问题,Cell动态高度计算可以去看看 sunny 的这篇文章介绍,今天主要和大家分享下我在使用 systemLayoutSizeFittingSize 系统自带方法计算高度的一些心得!"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return listArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = self.cell;
    cell.myLabel.text = listArr[indexPath.row];
    cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    return fittingHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    self.cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (self.cell == nil) {
        UINib *nib = [UINib nibWithNibName:@"MyTableViewCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
        self.cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    self.cell.myLabel.backgroundColor = [UIColor blueColor];
    self.cell.myLabel.textColor = [UIColor whiteColor];
    self.cell.myLabel.text = [listArr objectAtIndex:indexPath.row];
    return self.cell;
}

@end

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值