美文网首页dummy UI灵感iOS开发程序员
iOS自定义单元格之故事板

iOS自定义单元格之故事板

作者: 亦枫 | 来源:发表于2016-02-17 18:59 被阅读976次

    记录一个菜鸟的iOS学习之旅,如能帮助正在学习的你,亦枫不胜荣幸;如路过的大神如指教几句,亦枫感激涕淋!

    iOS系统提供了多种样式的表视图单元格样式,包含了基本的图片(UIImageView)、一级标题、二级标题和拓展视图等控件。同时,我们也可以通过自定义单元格实现更为丰富的表视图样式。

    iOS自定义单元格有三种基本的方式,代码实现、xib文件、故事板。本文就以上一篇文章中的例子为模板,教大家学习如何通过故事板文件自定义表视图的单元格样式。

    我们在 Document Outline 窗口中选择TableView目录下面的Custom Cell文件,从控件库中拖拽一个图片控件和文本控件到设计界面TableView里面prototype cells中,如图所示:

    interface builder.png

    然后创建自定义单元格类CustomCell.h和CustomCell.m文件,具体操作过程为:右击工程,选择New File选项,选择iOS —— Source —— Cocoa Touch Class模板:

    选择模板.png

    下一步,输入类名,如CustomCell,父类选择UITableViewCell类,下一步完成即可:

    新建文件.png

    这样,自定义单元格的.h头文件和.m实现文件就自动生成了。打开故事板文件,选择 Document Outline 窗口中的Custom Cell文件,选择右侧工具栏中的标识检测器,在class属性中选择我们刚刚新建的CustomCell类,再打开属性检测器,设置可重用标识符Identifier属性为“CustomCell”,方便代码中创建可重用单元格。

    Identifier属性.png

    为刚才在prototype cells单元格添加的图片和文本控件设置输出口,具体怎么快捷添加输出口部分的代码可以参考《iOS学习之旅》前面写的文章,添加完成之后CustomCell.h和CustomCell.m的代码如下:

    #import <UIKit/UIKit.h>
    
    @interface CustomCell : UITableViewCell
    
    @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    @property (weak, nonatomic) IBOutlet UILabel *title;
    
    @end
    
    #import "CustomCell.h"
    
    @implementation CustomCell
    
    @end
    

    接下来就可以修改ViewController.m视图控制器中的代码了,主要是创建单元格部分,将单元格对象所属的类替换成我们自定义的CustomCell类,可重用标识符换位故事板文件中定义的Identifier属性值:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        static NSString *identifierString = @"simpleTableViewCell";
        CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierString];
    //    if (cell==nil) {
    //        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierString];
    //    }
        NSInteger rowIndex = [indexPath row];
        NSDictionary *cellDictionary = [self.simpleData objectAtIndex:rowIndex];
        cell.title.text = [cellDictionary objectForKey:@"name"];
        cell.imageView.image = [UIImage imageNamed:[cellDictionary objectForKey:@"cover"]];
    
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        return cell;
    }
    

    这样,通过修改上篇文章中的实例代码,就实现了自定义单元格的功能,运行效果如下:

    运行效果.png

    本文只是简单的设计了自定义单元格,注重于学习功能的使用,至于更为丰富的单元格样式,大家可以自己发挥想象,自由设计。

    相关文章

      网友评论

      本文标题:iOS自定义单元格之故事板

      本文链接:https://www.haomeiwen.com/subject/bnrmkttx.html