iOS 使用 sdlayout 进行tableview cell 的自适应大小

这个问题困扰了我好久,ios还没有很好的入门,比起Android开发总有些懵逼的感觉。

第一步导入:

iOS 使用 sdlayout 进行tableview cell 的自适应大小_第1张图片

第二步 保证有两个model 一个是列表的数据源(Android里面是list数据,iOS 里面是NSMutableArray),另一个是单个条目的数据(我给它起名叫 itemData)
softContentDatas 在tableview中 —-从网络获取并转储的
itemData 在cell 中

iOS 使用 sdlayout 进行tableview cell 的自适应大小_第2张图片

iOS 使用 sdlayout 进行tableview cell 的自适应大小_第3张图片

第三步在tableview 的 heightForRowAtIndexPath中设置这个:

  • `/**
  • 设置单元格的高度

  • */
    • (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath {
      return [self.tableView cellHeightForIndexPath:indexPath model:_softContentDatas[indexPath.row] keyPath:@”itemData” cellClass:[FMTestTableViewCell class] contentViewWidth: [self cellContentViewWith]];
      }`

`
其中:model指的是cell的数据 –softContentDatas(第几个)
keyPath 是cell里面声明的itemData属性名字

第四步cell的数据set方法中设置底部边距:

-(void) setItemData:(SoftDetail *)itemData{
    if (itemData!=nil) {
        NSLog(@"hahahah:%@",itemData.imgurl);
        //图片
        if ([itemData.tag intValue] == 0 ) {
            _img.hidden = NO;
            _lable1.hidden =YES;
             [self.img sd_setImageWithURL:[NSURL URLWithString:itemData.imgurl] placeholderImage:[UIImage imageNamed:@"default_49_11"]];
            [self setupAutoHeightWithBottomView:_img bottomMargin:10];
        }
        if ([itemData.tag intValue]== 1 && itemData.content!= nil) {
            _img.hidden = YES;
            _lable1.hidden =NO;
            _lable1.text = itemData.content;
            [self setupAutoHeightWithBottomView:_lable1 bottomMargin:10];
        }
    }
}

下面贴出tableview和cell的代码片段:

//
//  FMDetailViewController.m
//  Sticker-Eye
//
//  Created by eye on 2018/7/17.
//  Copyright © 2018年 EyeCloud. All rights reserved.
//

#import "FMDetailViewController.h"
#import "FMTestTableViewCell.h"
#import 
#import 
#import 
#import "SoftDetail.h"
#import "UIView+SDAutoLayout.h"
#import 

@interface FMDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *softContentDatas;
@property (nonatomic, strong) NSMutableDictionary *heightAtIndexPath;//缓存高度



@end

@implementation FMDetailViewController
#pragma mark -- 懒加载数组
-(NSMutableArray *) softContentDatas{
    if (!_softContentDatas) {
        _softContentDatas = [NSMutableArray new];
    }
    return _softContentDatas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getNetData];
    [self setupTitleBar];
    [self initLayout];
    // Do any additional setup after loading the view from its nib.
}

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

-(void)setupTitleBar{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"Sticker-Eye";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#007bee"],NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    // Do any additional setup after loading the view from its nib.
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20 , 20)];

    [btn setBackgroundImage:[UIImage imageNamed:@"camera_setting_4"] forState:UIControlStateNormal];
    // 让按钮内部的所有内容左对齐
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [btn addTarget:self action:@selector(gotoMain) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(gotoMain)];

}
-(void) initLayout{
    self.tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight-64-44) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];



}
-(void) gotoMain{
    [self dismissViewControllerAnimated:YES completion:nil];

}
/**
 *  UITableViewDataSource协议中的所有方法,用来对表格视图的样式进行设置(比如说显示的分区个数、每个分区中单元格个数、单元格中显示内容、分区头标题、分区未标题、分区的View)
 */
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
/**
 *  设置每个分区显示的行数
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _softContentDatas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ///<1.>设置标识符
    static NSString * str1 = @"cell_text";
    ///<2.>复用机制:如果一个页面显示7个cell,系统则会创建8个cell,当用户向下滑动到第8个cell时,第一个cell进入复用池等待复用。
    FMTestTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str1];
    ///<3.>新建cell
    if (cell == nil) {
        //副标题样式
        cell = [[FMTestTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str1];
        // 2
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        // 3点击没有颜色改变
        cell.selected = NO;
    }

    if (_softContentDatas!=nil) {
        NSLog(@"hahah:%ld",(long)indexPath.row);
        cell.itemData = _softContentDatas[indexPath.row];
    }
//    cell.data = self.softDatas[indexPath.section];
    ///<4.>设置单元格上显示的文字信息
    //    if (indexPath.section == 0) {
    //        cell.textLabel.text = @"hahah";
    //    } else {
    //        cell.textLabel.text = @"gegege";
    //    }
    //
    //    cell.detailTextLabel.text = @"副标题";

    return cell;
}
/**
 *  设置单元格的高度
 *  
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {



    return [self.tableView cellHeightForIndexPath:indexPath model:_softContentDatas[indexPath.row] keyPath:@"itemData" cellClass:[FMTestTableViewCell class] contentViewWidth: [self cellContentViewWith]];


}


//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    NSNumber *height = @(cell.frame.size.height);
//    [self.heightAtIndexPath setObject:height forKey:indexPath];
//}


-(void)getNetData{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
     manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"articleId"] =@"1";
    [manager POST:@"http://www.godboy.cn/app/getSoftContent.do" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功:%@",responseObject);
        if([responseObject[@"status"]intValue] ==200) {
            NSMutableArray *data = responseObject[@"data"];

            self.softContentDatas =[SoftDetail mj_objectArrayWithKeyValuesArray:data];

            [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误:%@",error);
    }];

}
- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;

    // 适配ios7横屏
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

cell 的代码

//
//  FMTestTableViewCell.m
//  Sticker-Eye
//
//  Created by eye on 2018/7/20.
//  Copyright © 2018年 EyeCloud. All rights reserved.
//

#import "FMTestTableViewCell.h"
#import 
#import 

@implementation FMTestTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code

}

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

    // Configure the view for the selected state
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self initSubView];
    }
    return self;
}
-(void) initSubView{

    _img = [[UIImageView alloc] init];
    [self.contentView addSubview:_img];
    _img.sd_layout
    .widthIs(screenWidth)
    .heightIs(150)
     .heightRatioToView(self, 1)
    ;
    _lable1 = [[UILabel alloc] init];

    [self.contentView addSubview:_lable1];
    _lable1.backgroundColor = [UIColor redColor];
    _lable1.text=@"hahahahhhhhhhahahahahahahhahhahahahahahhahahhahaahhahahahah   ahahahhahahahhahah  h ahhahahahahh hahahaaha";
    _lable1.textColor =[UIColor blackColor];
    _lable1.textAlignment = NSTextAlignmentLeft;
    _lable1.font = [UIFont systemFontOfSize:12];
    _lable1.sd_layout
    .widthIs(screenWidth)
    .heightIs(50)
    .topSpaceToView(self.contentView, 10)
    .leftSpaceToView(self.contentView, 10)



    ;


}
-(void) setItemData:(SoftDetail *)itemData{
    if (itemData!=nil) {
        NSLog(@"hahahah:%@",itemData.imgurl);
        //图片
        if ([itemData.tag intValue] == 0 ) {
            _img.hidden = NO;
            _lable1.hidden =YES;
             [self.img sd_setImageWithURL:[NSURL URLWithString:itemData.imgurl] placeholderImage:[UIImage imageNamed:@"default_49_11"]];
            [self setupAutoHeightWithBottomView:_img bottomMargin:10];
        }
        if ([itemData.tag intValue]== 1 && itemData.content!= nil) {
            _img.hidden = YES;
            _lable1.hidden =NO;
            _lable1.text = itemData.content;
            [self setupAutoHeightWithBottomView:_lable1 bottomMargin:10];
        }
    }
}
@end
//
//  FMTestTableViewCell.h
//  Sticker-Eye
//
//  Created by eye on 2018/7/20.
//  Copyright © 2018年 EyeCloud. All rights reserved.
//

#import 
#import "SoftDetail.h"

@interface FMTestTableViewCell : UITableViewCell
@property(strong,nonatomic) SoftDetail  *itemData;
@property(strong,nonatomic) UIImageView  *img;
@property(strong,nonatomic) UILabel  *lable1;
@end

你可能感兴趣的:(ios)