iOS中Masonry和UITableView+FDTemplateLayoutCell结合使用

Masonry的github链接:https://github.com/SnapKit/Masonry
UITableView-FDTemplateLayoutCell github:https://github.com/forkingdog/UITableView-FDTemplateLayoutCell
注意:图片及json数据来自UITableView-FDTemplateLayoutCell的demo里面的。
具体代码如下:

一:控制器中创建视图,处理数据

//
//  ViewController.m
//  BJTTest
//
//  Created by yunlong on 17/4/28.
//  Copyright © 2017年 yunlong. All rights reserved.
//
#import "ViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "FDFeedEntity.h"
#import "FDFeedCell.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong) UITableView *myTableView;
//数据源
@property (nonatomic, strong) NSMutableArray *feedEntitySections;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.myTableView];

    self.myTableView.dataSource = self;
    self.myTableView.delegate   = self;
    //注册cell
    [self.myTableView registerClass:[FDFeedCell class] forCellReuseIdentifier:@"FDFeedCell"];

    self.myTableView.estimatedRowHeight = 200;//预算行高
    self.myTableView.fd_debugLogEnabled = YES;//开启log打印高度
    [self buildTestDataThen:^{
     //刷新数据
        [self.myTableView reloadData];
    }];
}
#pragma mark - 处理数据
- (void)buildTestDataThen:(void (^)(void))then{
    // Simulate an async request
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Data from `data.json`
        NSString *dataFilePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:dataFilePath];
        NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *feedDicts = rootDict[@"feed"];

        // Convert to `FDFeedEntity`
        NSMutableArray *entities = @[].mutableCopy;
        [feedDicts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [entities addObject:[[FDFeedEntity alloc] initWithDictionary:obj]];
        }];
        self.feedEntitySections = entities;

        // Callback
        dispatch_async(dispatch_get_main_queue(), ^{
            !then ?: then();
        });
    });
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FDFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FDFeedCell" forIndexPath:indexPath];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(FDFeedCell *)cell atIndexPath:(NSIndexPath *)indexPath{
    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    if (indexPath.row % 2 == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    cell.entity = self.feedEntitySections[indexPath.row];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //高度计算并且缓存
    return [tableView fd_heightForCellWithIdentifier:@"FDFeedCell" cacheByIndexPath:indexPath configuration:^(FDFeedCell *cell) {
        [self configureCell:cell atIndexPath:indexPath];
    }];
}

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

@end

二:自定义cell及代码的实现
(1).h文件


#import <UIKit/UIKit.h>

@class FDFeedEntity;
@interface FDFeedCell : UITableViewCell
@property (nonatomic, strong) FDFeedEntity *entity;
@end

(2).m文件

#import "FDFeedCell.h"
#import "FDFeedEntity.h"
#import <Masonry/Masonry.h>
#define margin 4
#define padding 10
@interface FDFeedCell ()
@property (nonatomic, strong)  UILabel *titleLabel;
@property (nonatomic, strong)  UILabel *contentLabel;
@property (nonatomic, strong)  UIImageView *mainImageView;
@property (nonatomic, strong)  UILabel *userNameLabel;
@property (nonatomic, strong)  UILabel *timeLabel;

@end

@implementation FDFeedCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setAutoLayout];
    }
    return self;
}
#pragma mark - 布局
- (void)setAutoLayout{
    _titleLabel                    = [[UILabel alloc] init];
    _titleLabel.numberOfLines = 0;
    //_titleLabel.backgroundColor    = [UIColor redColor];
    [self.contentView addSubview:_titleLabel];

    _contentLabel                  = [[UILabel alloc] init];
    _contentLabel.numberOfLines    = 0;
    _contentLabel.font             = [UIFont systemFontOfSize:14];
    _contentLabel.textColor        = [UIColor grayColor];
    //_contentLabel.backgroundColor  = [UIColor purpleColor];
    [self.contentView addSubview:_contentLabel];

    _mainImageView                 = [[UIImageView alloc] init];
    _mainImageView.contentMode     = UIViewContentModeScaleAspectFill;
    _mainImageView.clipsToBounds   = YES;
    //_mainImageView.backgroundColor = [UIColor orangeColor];
    [self.contentView addSubview:_mainImageView];

    _userNameLabel                 = [[UILabel alloc] init];
    //_userNameLabel.backgroundColor = [UIColor greenColor];
    _userNameLabel.textColor       = [UIColor orangeColor];
    _userNameLabel.font            = [UIFont systemFontOfSize:12];
    [self.contentView addSubview:_userNameLabel];

    _timeLabel                     = [[UILabel alloc] init];
    _timeLabel.textColor           = [UIColor blueColor];
    _timeLabel.font                = [UIFont systemFontOfSize:12];
    //_timeLabel.backgroundColor     = [UIColor blueColor];
    [self.contentView addSubview:_timeLabel];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.mas_equalTo(self.contentView).offset(padding);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-padding);
    }];

    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.titleLabel);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(margin);
    }];

    [_mainImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLabel.mas_left);
        make.top.mas_equalTo(self.contentLabel.mas_bottom).offset(margin);
    }];

    [_userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLabel.mas_left);
        make.top.mas_equalTo(self.mainImageView.mas_bottom).offset(margin);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-margin);
    }];

    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.mas_equalTo(self.userNameLabel);
        make.right.mas_equalTo(self.titleLabel.mas_right);
    }];
}
#pragma mark - 赋值
- (void)setEntity:(FDFeedEntity *)entity{
    _entity = entity;
    self.titleLabel.text     = entity.title;
    self.contentLabel.text   = entity.content;
    self.mainImageView.image = entity.imageName.length > 0 ? [UIImage imageNamed:entity.imageName] : nil;
    self.userNameLabel.text  = entity.username;
    self.timeLabel.text      = entity.time;
}

三:model就是用UITableView-FDTemplateLayoutCell的demo里面的model
(1).h文件

#import <Foundation/Foundation.h>

@interface FDFeedEntity : NSObject

- (instancetype)initWithDictionary:(NSDictionary *)dictionary;

@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *content;
@property (nonatomic, copy) NSString *username;
@property (nonatomic, copy) NSString *time;
@property (nonatomic, copy) NSString *imageName;

@end

(1).m文件

#import "FDFeedEntity.h"

@implementation FDFeedEntity

- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
    self = super.init;
    if (self) {
        _identifier = [self uniqueIdentifier];
        _title = dictionary[@"title"];
        _content = dictionary[@"content"];
        _username = dictionary[@"username"];
        _time = dictionary[@"time"];
        _imageName = dictionary[@"imageName"];
    }
    return self;
}

- (NSString *)uniqueIdentifier
{
    static NSInteger counter = 0;
    return [NSString stringWithFormat:@"unique-id-%@", @(counter++)];
}

@end

五:效果图
这里写图片描述

猜你喜欢

转载自blog.csdn.net/techalleyboy/article/details/70918117