一、自定义Cell

  • 为什么需要自定义cell:系统提供的cell满足不了复杂的样式,因此:自定义Cell和自定义视图一样,自己创建一种符合我们需求的Cell并使用这个Cell。如下图所示的这些Cell都是通过自定义Cell样式实现的:
  • 自定义Cell的步骤:

    1.首先创建一个继承于UITableViewCell的类:(这是一个简易的通讯录的自定义cell)

  1. @interface RootTableViewCell : UITableViewCell
  2. // 联系人头像
  3. @property (nonatomic, strong) UIImageView *headerImageView;
  4. // 联系人姓名label
  5. @property (nonatomic, strong) UILabel *nameLabel;
  6. // 电话号码的label
  7. @property (nonatomic, strong) UILabel *phoneLabel;
  8. @end

    2.实现UITableViewCell的初始化方法:

  1. @implementation RootTableViewCell
  2. - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  3. {
  4. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  5. if (self) {
  6. // 初始化子视图
  7. [self initLayout];
  8. }
  9. return self;
  10. }
  11.  
  12. - (void)initLayout
  13. {
  14. // 1.头像
  15. self.headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(, , , )];
  16. // self.headerImageView.backgroundColor = [UIColor orangeColor];
  17. self.headerImageView.layer.masksToBounds = YES;
  18. self.headerImageView.layer.cornerRadius = ;
  19. // cell提供了一个contentView的属性,专门用来自定义cell,防止在cell布局的时候发生布局混乱,如果是自定义cell,记得将子控件添加到ContentView上
  20. [self.contentView addSubview:self.headerImageView];
  21.  
  22. // 2.姓名
  23. self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.headerImageView.frame) + , CGRectGetMinY(self.headerImageView.frame), , )];
  24. // self.nameLabel.backgroundColor = [UIColor redColor];
  25. [self.contentView addSubview:self.nameLabel];
  26.  
  27. // 3.电话号码
  28. self.phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + , , )];
  29. // self.phoneLabel.backgroundColor = [UIColor greenColor];
  30. [self.contentView addSubview:self.phoneLabel];
  31.  
  32. }
  • 注意:
  • 确保所有的你想添加的子视图都在自定义Cell的初始化方法中创建,由于UITableView的重用机制,一个Cell在第一次创建成功并用于下一次显示的时候,不会再走初始化方法,这样可以避免子视图的重复创建。
  • 在Cell的子视图创建成功后,将子视图设置为属性,类似于UITableViewCell所自带的textLabel和detailTextLabel属性。便于在UITableView的协议中给自定义视图赋值。

二、Model类型对象的使用

  • Model类概述:
  • Model类主要是为了给我们提供数据,简单的说即自定义类且继承于NSObject的称之为Model。(前面OC学到的KVC就是帮助我们将字典转换为Model类。)
  • 在自定义Cell中使用Model类存放数据:
  • 首先创建Model类并继承于NSObject
  • 然后添加和字典中对应的属性
  • 在视图控制器中将字典通过KVC为Model赋值
  • 将Model对象添加到数组中并刷新TableView
  1. // 建立model存放数据
  2. @interface Contact : NSObject
  3. // 姓名
  4. @property (nonatomic, copy) NSString *name;
  5. // 手机号码
  6. @property (nonatomic, copy) NSString *phoneNumber;
  7. // 图片名
  8. @property (nonatomic, copy) NSString *imageName;
  9. @end
  1. #import "RootTableViewController.h"
  2. #import "Contact.h"
  3. #import "RootTableViewCell.h"
  4. @interface RootTableViewController ()
  5. // 声明一个大数组存放所有联系人
  6. @property (nonatomic, strong) NSMutableArray *allContactsArray;
  7.  
  8. @end
  9.  
  10. @implementation RootTableViewController
  11. // 懒加载 (重写getter方法)
  12. - (NSMutableArray *)allContactsArray
  13. {
  14. if (_allContactsArray == nil) {
  15. _allContactsArray = [NSMutableArray array];
  16. }
  17. return _allContactsArray;
  18. }
  19.  
  20. - (void)viewDidLoad {
  21. [super viewDidLoad];
  22. self.title = @"通讯录";
  23. self.navigationController.navigationBar.barTintColor = [UIColor lightGrayColor];
  24. [self handleData];
  25.  
  26. }
  27.  
  28. - (void)handleData
  29. {
  30. // 读取plist文件
  31. NSMutableArray *array =[NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Contacts" ofType:@"plist"]];
  32. // 将要显示的数据转为model对象
  33. for (NSDictionary *contactDict in array) {
  34. Contact *contact = [[Contact alloc] init];
  35. // 使用KVC赋值
  36. [contact setValuesForKeysWithDictionary:contactDict];
  37. // 将联系人model存放在大数组中
  38. [self.allContactsArray addObject:contact];
  39. }
  40.  
  41. }
  42.  
  43. - (void)didReceiveMemoryWarning {
  44. [super didReceiveMemoryWarning];
  45.  
  46. }
  47.  
  48. #pragma mark - Table view data source
  49.  
  50. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  51.  
  52. return self.allContactsArray.count;
  53. }
  54.  
  55. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  56.  
  57. ;
  58. }
  59.  
  60. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  61. {
  62. // 创建常量标识符
  63. static NSString *identifier = @"cell";
  64. // 从重用队列里查找可重用的cell
  65. RootTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  66. // 判断如果没有可以重用的cell,创建
  67. if (!cell) {
  68. cell = [[RootTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
  69. }
  70. // 设置数据
  71. // 取出model对象
  72. Contact *contact = self.allContactsArray[indexPath.section];
  73. cell.headerImageView.image = [UIImage imageNamed:contact.imageName];
  74. cell.nameLabel.text = contact.name;
  75. cell.phoneLabel.text = contact.phoneNumber;
  76. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  77. return cell;
  78. }
  79.  
  80. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  81. {
  82. ;
  83.  
  84. }
  85.  
  86. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  87. {
  88. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  89.  
  90. }
  91.  
  92. @end

  3.运行效果如下图:

三、多种Cell混合使用

  • 一个重用标识符只能针对于一种Cell样式,不同的Cell需要基于不同的重用标识符来进行区分,而重用标识符的区分需要根据不同的情况来划分,比如:
  • model属性划分(不同的数据内容,比如一个数据中有type字段,为1代表图片类型,为0代表文字类型等)
  • 固定的行显示的Cell类型不一样
  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  2. static NSString *identifier1 = @"labelCell";
  3. static NSString *identifier2 = @"imageCell";
  4. Person *person = self.allPersonsArray[indexPath.row];
  5. "]) {
  6. LableCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1 forIndexPath:indexPath];
  7. cell.nameLabel.text = person.name;
  8. cell.statusLabel.text = person.status;
  9. return cell;
  10.  
  11. }else {
  12. ImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2 forIndexPath:indexPath];
  13. cell.nameLabel.text = person.name;
  14. cell.statusLabel.text = person.status;
  15. cell.myImageView.image = [UIImage imageNamed:person.imageName];
  16. return cell;
  17. }
  18.  
  19. }

四、Cell自适应高度

  • 当每个Cell都有不同的高度时,就需要Cell去自适应高度
  • 方式为两种:
  • 文本自适应高度:根据文本内容设定Label高度
  • 图片自适应高度:根据图片宽度进行等比例缩放
  • 这里需要创建一个新的类去封装这两个方法用以获得文本的高度和图片的高度:
  1. @interface CalculateTextHeight : NSObject
  2.  
  3. // 声明类方法用来计算文本高度
  4. + (CGFloat)calculateTextHeightWithText:(NSString *)text
  5. font:(UIFont *)font;
  6.  
  7. + (CGFloat)imageHeightWithImage:(UIImage *)image;
  8.  
  9. @end
  • 具体的实现
  1. @implementation CalculateTextHeight
  2. + (CGFloat)calculateTextHeightWithText:(NSString *)text font:(UIFont *)font
  3. {
  4. // iOS7.0中求文本高度的方法,返回一个CGRect的高度
  5.  
  6. // 第一个参数,一个屏幕宽,10000高的文本
  7. CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, );
  8. // 第二个参数,设置以行高为单
  9. // 第三个参数,根据字体判断高度
  10. CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil];
  11.  
  12. return rect.size.height;
  13.  
  14. }
  15.  
  16. + (CGFloat)imageHeightWithImage:(UIImage *)image
  17. {
  18. // 得到图片的宽和高
  19. CGFloat width = image.size.width;
  20. CGFloat height = image.size.height;
  21. // 得到宽高比例和屏幕宽度
  22. float i = height / width;
  23. float j = [UIScreen mainScreen].bounds.size.width;
  24. CGFloat x = i * j;
  25. return x;
  26. }
  27.  
  28. @end
  1.  

iOS学习之UI自定义cell的更多相关文章

  1. iOS学习之UI可视化编程-XIB

    一.Interface Builder可视化编程 1.Interface Builder简介: GUI:图形用户界面(Graphical User Interface,简称GUI,又称图形用户接口)是 ...

  2. iOS学习之UI可视化编程-StoryBoard

    一.StoryBoard与xib 对比: 相同点:都属于IB编程的方式,可以快速构建GUI. 不同点:xib侧重于单文件(单独的控制器或者视图)编辑,storyboard侧重于多页面关联.storyb ...

  3. iOS学习之UITableView中Cell的操作

    接着iOS学习之Table View的简单使用 这篇,这里主要讲UITableView 中的Cell的操作,包括标记.移动.删除.插入. 为了简单快捷,直接从原来那篇的代码开始,代码下载地址:http ...

  4. iOS 中使用 XIB 自定义cell 的两种方法 以及 编译出现常见 的错误 ++++(xcode6.0之后)

    一. 注册cell 1.创建自定义cell并勾选 xib :(勾选xib就会自动生成与cell文件关联的xib) 2.在 tableViewController里注册自定义Cell (或者遵守tabl ...

  5. iOS 中使用 XIB 自定义cell的两种方法以及编译出现常见 的错误 (xcode6.0之后)

    一. 注册cell 1.创建自定义cell并勾选 xib :(勾选xib就会自动生成与cell文件关联的xib) 2.在 tableViewController里注册自定义Cell (或者遵守tabl ...

  6. iOS开发总结-UITableView 自定义cell和动态计算cell的高度

    UITableView cell自定义头文件:shopCell.h#import <UIKit/UIKit.h>@interface shopCell : UITableViewCell@ ...

  7. iOS 学习 - 18.TextField 自定义菜单事件,复制和微信分享

    菜单事件包括,剪切.拷贝.全选.分享...,此 demo 只有 copy.share 1.定义 field 继承与 UITextField - (BOOL)canPerformAction:(SEL) ...

  8. iOS深入学习(UITableView系列4:使用xib自定义cell)

    可以通过继承UITableViewCell重新自定义cell,可以像下面一样通过代码来自定义cell,但是手写代码总是很浪费时间, ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

  9. AJ学IOS(17)UI之纯代码自定义Cell实现新浪微博UI

    AJ分享,必须精品 先看效果图 编程思路 代码创建Cell的步骤 1> 创建自定义Cell,继承自UITableViewCell 2> 根据需求,确定控件,并定义属性 3> 用get ...

随机推荐

  1. Android多线程异步处理:AsyncTask 的实现原理

    AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法.注意继承时需要设定三个泛型P ...

  2. a mystrious max subquence sum

    #include<cstdio>#include<cstring>const int maxn=100005;int buf[maxn];int main(){ freopen ...

  3. CSS 中 display:inline-block 属性使用详解

    本文详细描述了display:inline-block的基础知识,产生的问题和解决方法以及其常见的应用场景,加深了对inline-block应用的进一步理解. 基础知识 display:inline- ...

  4. C# 加密算法

     public static class Common     {         #region MD5加密         /// <summary>            /// M ...

  5. IE6-IE9兼容性问题列表及解决办法总结

    IE6-IE9兼容性问题列表及解决办法总结 概述 第一章:HTML. 3 第一节:IE7-IE8更新... 31.如果缺少结束标记的 P 元素后跟 TABLE.FORM.NOFRAMES 或 NOSC ...

  6. 码农谷 求前N项之和

    题目描述 有一分数序列:2/1.3/2.5/3.8/5.13/8.21/13.......求出这个数列的前N项之和,保留两位小数. 输入描述 N 输出描述 数列前N项和 样例 输入: 输出: 16.4 ...

  7. Apache开启rewrite

    1.找到LoadModule rewrite_module modules/mod_rewrite.so去掉前面的#号 2.找到AllowOverride None 改为:AllowOverride ...

  8. .NET常用类库知识总结

    常用类库之.NET中的字符串 字符串的特性 1.不可变性        由于字符串是不可变的的,每次修改字符串,都是创建了一个单独字符串副本(拷贝了一个字符串副本).之所以发生改变只是因为指向了一块新 ...

  9. kbengine mmo源码(完整服务端源码+资源+完整客户端源码)

      本项目作为kbengine服务端引擎的客户端演示而写 更新kbengine插件库(https://github.com/kbengine/kbengine_unity3d_plugins):    ...

  10. Mysql的ssl主从复制+半同步主从复制

    Mysql的ssl主从复制+半同步主从复制 准备工作 1.主从服务器时间同步 [root@localhost ~]# crontab -e */30 * * * * /usr/sbin/ntpdate ...