IOS自定义UITableView框架(社区风格)

效果展示

·

进入构建结构

首先我们新建一个工程

接下来我们拖进来一个Table View Controller,将Storyboard Entry Point指向我们的Table View Controller。原来的ViewController就可以删除了。效果如图所示

选中Table View Controller,点击上面菜单栏中Editor->Embed in->Navigation Controller

基本的工作我们都做完了,可以讲工程中没用的东西都可以删除了,方便我们进行编写东西

主题(代码编写)

在这里我进行代码的编写,讲述主要部分,后面会把完整的项目给出

构建LDEntity用来初始化字典,进行Json数据的解析

LDEntity.h

#import <Foundation/Foundation.h>

@interface FDFeedEntity : NSObject

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

@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

-(instancetype)initWithDictionary:(NSDictionary *)dictionary方法的具体实现,返回本身类型

LDEntity.m

#import "FDFeedEntity.h"

@implementation FDFeedEntity

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

@end

以上代码的功能主要是为了解析JSON数据

构建我们的Main.storyboard

选中Table View更改Style为Grouped

设计出以下样式,并且使用 auto layout进行约束

接下来编写cell

新建LDCell 继承 UITableViewCell

将Main.storyboard中TableView中的Cell的Identifier设置为LDCell,并且关联LDCell

LDCell.h

构建一个LDEntity对象解析数据

#import <UIKit/UIKit.h>
#import "LDEntity.h"

@interface LDCell : UITableViewCell

@property(nonatomic,strong)LDEntity *entity;

@end

将刚才的所有控件与LDCell.m关联

在LDCell.m中构建entity的set方法,还有需要注意的是如果你没有使用auto layout,你需要重写约束方法

LDCell.m

#import "LDCell.h"

@interface LDCell ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UIImageView *contentImageView;
@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@end

@implementation LDCell

- (void)awakeFromNib {
    // 修复IOS7中的BUG- 初始化 constraints warning

    self.contentView.bounds = [UIScreen mainScreen].bounds;
}

//关联控件进行数据显示
-(void)setEntity:(LDEntity *)entity{
    _entity = entity;

    self.titleLabel.text = entity.title;
    self.contentLabel.text = entity.content;
    self.contentImageView.image = entity.imageName.length > 0 ? [UIImage imageNamed:entity.imageName] : nil;
    self.usernameLabel.text = entity.username;
    self.timeLabel.text = entity.time;
}

#if 0

// 如果没有使用 auto layout, 请重写这个方法
- (CGSize)sizeThatFits:(CGSize)size
{
    CGFloat totalHeight = 0;
    totalHeight += [self.titleLabel sizeThatFits:size].height;
    totalHeight += [self.contentLabel sizeThatFits:size].height;
    totalHeight += [self.contentImageView sizeThatFits:size].height;
    totalHeight += [self.usernameLabel sizeThatFits:size].height;
    totalHeight += 40; // margins
    return CGSizeMake(size.width, totalHeight);
}

#endif

@end

开始编写我们最重要的类LDViewController.在编写这个类之前,我们需要使用FDTemplateLayoutCellFDTemplateLayoutCell

,并且将TableViewController与LDViewController进行关联

LDViewController.h

#import <UIKit/UIKit.h>

@interface FDFeedViewController : UITableViewController

@end

TableView的使用有不明白的可以去学习下,这里不做解释了,注释中给出了重点的地方讲解,设置data source以及设置Delegate在程序中做出区分

LDViewController.m


#import "LDViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LDEntity.h"
#import "LDCell.h"

@interface LDViewController ()<UIActionSheetDelegate>

@property (nonatomic, copy) NSArray *prototypeEntitiesFromJSON;
@property (nonatomic, strong) NSMutableArray *feedEntitySections; // 2d array
@property (nonatomic, assign) BOOL cellHeightCacheEnabled;

@end

@implementation LDViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 200;
    self.tableView.fd_debugLogEnabled = YES;

    self.cellHeightCacheEnabled = YES;

    [self buildTestDataThen:^{
        self.feedEntitySections = @[].mutableCopy;
        [self.feedEntitySections addObject:self.prototypeEntitiesFromJSON.mutableCopy];
        [self.tableView reloadData];
    }];
}

- (void)buildTestDataThen:(void (^)(void))then
{
    // 模拟一个异步请求
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // 读取数据从 `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"];

        // 讲数据转化为 `LDEntity`
        NSMutableArray *entities = @[].mutableCopy;
        [feedDicts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [entities addObject:[[LDEntity alloc] initWithDictionary:obj]];
        }];
        self.prototypeEntitiesFromJSON = entities;

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

//设置数据源
#pragma mark - Table view data source

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //LDCell为Main.storyboard中的cell控件
    LDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LDCell" forIndexPath:indexPath];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(LDCell *)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.section][indexPath.row];
}

//设置委托
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.cellHeightCacheEnabled) {

        //LDCell为Main.storyboard中的cell控件

        return [tableView fd_heightForCellWithIdentifier:@"LDCell" cacheByIndexPath:indexPath configuration:^(LDCell *cell) {
            [self configureCell:cell atIndexPath:indexPath];
        }];
    } else {
        return [tableView fd_heightForCellWithIdentifier:@"LDCell" configuration:^(LDCell *cell) {
            [self configureCell:cell atIndexPath:indexPath];
        }];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSMutableArray *mutableEntities = self.feedEntitySections[indexPath.section];
        [mutableEntities removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end

如果你想有自己的cell,你可以这么做:


#import "UITableView+FDTemplateLayoutCell.h"

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"reuse identifer" configuration:^(id cell) {
        // 配置此Cell(单元格)的数据, 同你在"-tableView:cellForRowAtIndexPath:"做了什么一样
        // 像这样:
        //    cell.entity = self.feedEntities[indexPath.row];
    }];
}

下面制作我们的最后一个功能就是下拉刷新操作

我们使用UITableViewController自带的UIRefreshControl

在LDViewController.m中添加此方法,并且与UIRefreshControl关联

//重新加载数据

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.feedEntitySections removeAllObjects];
        [self.feedEntitySections addObject:self.prototypeEntitiesFromJSON.mutableCopy];
        [self.tableView reloadData];
        [sender endRefreshing];
    });

效果如下:

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-27 12:20:19

IOS自定义UITableView框架(社区风格)的相关文章

IOS 自定义UITableView

根据不同需要,需要使用tableview的结构,但是里面每一个cell,又需要自己的样式,所以学习了一下怎样把自己定义的cell加到tableview里面 首先要自己创建一个类,继承UITableViewCell,然后新建一个空的xib文件,并在class属性设置为对应的类名 代码部分: <pre name="code" class="objc"> #import "SettingViewController.h" #import &

iOS 自定义UITableView 删除View

替朋友解决的问题: 需要修改左拉,删除的按钮 查看SDK,系统自带的,只能修改NSStrin 那么问题来了...他急!!! 所以,我就只好用第三方快速开发. 使用SWTableViewCell来解决这个 pod 'SWTableViewCell', '~> 0.3.6' 具体访问GitHub上查看具体内容  地址链接 ==================================== 使用三方类库有风险,如若使用,风险由个人承担.

IOS UItableView得group风格如何去掉分割线问题

在自定义UItableView的时候,当选择的style为Group时,往往在设置透明后分割线还在,为了去除,只要重新设置一个BackgroundView覆盖掉原来的即可 //取消分割线 UIView *view= [ [ [ UIView  alloc ] init ] autorelease]; [cell setBackgroundView :view]; //取消点击效果 cell.selectionStyle = UITableViewCellSelectionStyleNone; I

【IOS】UITableView样式的自定义

很多时候,我们需要自定义UITableView来满足我们的特殊要求.这时候,关于UITableView和cell的自定义和技巧太多了,就需要不断的总结和归纳. 1.添加自定义的Cell. 这个问题已经涉及过,但是,这里要说的主要是两种方法的比较! 因为,我经常发现有两种方式: 1.xib方式 这种方式,也就是说,为自定义的UITableViewCell类添加一个xib的文件.并且让两者关联. 这时候,写法为: // 返回cell - (UITableViewCell *)tableView:(U

常用iOS的第三方框架

图像:1.图片浏览控件MWPhotoBrowser       实现了一个照片浏览器类似 iOS 自带的相册应用,可显示来自手机的图片或者是网络图片,可自动从网络下载图片并进行缓存.可对图片进行缩放等操作.      下载:https://github.com/mwaterfall/MWPhotoBrowser 目前比较活跃的社区仍旧是Github,除此以外也有一些不错的库散落在Google Code.SourceForge等地方.由于Github社区太过主流,这里主要介绍一下Github里面流

史上最全的常用iOS的第三方框架

文章来源:http://blog.csdn.net/sky_2016/article/details/45502921 图像:1.图片浏览控件MWPhotoBrowser       实现了一个照片浏览器类似 iOS 自带的相册应用,可显示来自手机的图片或者是网络图片,可自动从网络下载图片并进行缓存.可对图片进行缩放等操作.      下载:https://github.com/mwaterfall/MWPhotoBrowser 目前比较活跃的社区仍旧是Github,除此以外也有一些不错的库散落

我的女神——简洁实用的iOS代码调试框架

我的女神--简洁实用的iOS代码调试框架 一.引言 这篇博客的起源是接手了公司的一个已经完成的项目,来做代码优化,项目工程很大,并且引入了很多公司内部的SDK,要搞清楚公司内部的这套框架,的确不是件容易的事,并且由于这个项目是多人开发的,在调试阶段会打印出巨量的调试信息,使得浏览有用信息变的十分困难,更加恐怖的是,很多信息是SDK中的调试打印,将这些都进行注销是非常费劲甚至不可能的事,于是便有了这样一些需求:首先,我需要清楚了解各个controller之间的跳转关系,需要快速的弄清每个stroy

iOS自定义转场动画实战讲解

iOS自定义转场动画实战讲解 转场动画这事,说简单也简单,可以通过presentViewController:animated:completion:和dismissViewControllerAnimated:completion:这一组函数以模态视图的方式展现.隐藏视图.如果用到了navigationController,还可以调用pushViewController:animated:和popViewController这一组函数将新的视图控制器压栈.弹栈. 下图中所有转场动画都是自定义的

(转) IOS ASI http 框架详解

(转) IOS ASI http 框架详解 ASIHTTPRequest对CFNetwork API进行了封装,并且使用起来非常简单,用Objective-C编写,可以很好的应用在Mac OS X系统和iOS平台的应用程序中.ASIHTTPRequest适用于基本的HTTP请求,和基于REST的服务之间的交互. ASIHTTPRequest功能很强大,主要特色如下: l 通过简单的接口,即可完成向服务端提交数据和从服务端获取数据的工作 l 下载的数据,可存储到内存中或直接存储到磁盘中 l 能上传