iOS中Masonry和UITableView+FDTemplateLayoutCell結合使用 – iPhone手機開發 iPhone軟體開發教學課程

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 ()
@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 

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

(2).m文件

#import "FDFeedCell.h"
#import "FDFeedEntity.h"
#import 
#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 

@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

五:效果圖
這裡寫圖片描述

發佈留言