首页 > 其他分享 >UITableView 系列五 :自定义UITableViewCell (实例)

UITableView 系列五 :自定义UITableViewCell (实例)

时间:2023-05-12 13:32:52浏览次数:36  
标签:UITableViewCell tableView CustomCell self NSString 添加 UITableView copy 自定义


有时候我们需要自己定义UITableViewCell的风格,其实就是向行中添加子视图。添加子视图的方法主要有两种:使用代码以及从.xib文件加载。当然后一种方法比较直观。

我们这次要自定义一个Cell,使得它像QQ好友列表的一行一样:左边是一张图片,图片的右边是三行标签:

当然,我们不会搞得这么复杂,只是有点意思就行。

1、运行Xcode 4.2,新建一个Single View Application,名称为Custom Cell:

2、将图片资源导入到工程。为此,我找了14张50×50的.png图片,名称依次是1、2、……、14,放在一个名为Images的文件夹中。将此文件夹拖到工程中,在弹出的窗口中选中Copy items into…

添加完成后,工程目录如下:

3、创建一个UITableViewCell的子类:选中Custom Cell目录,依次选择File — New — New File,在弹出的窗口,左边选择Cocoa Touch,右边选择Objective-C class:

之后选择Next和Create,就建立了两个文件:CustomCell.h和CustomCell.m。

4、创建CustomCell.xib:依次选择File — New — New File,在弹出的窗口,左边选择User Interface,右边选择Empty:

单击Next,选择iPhone,再单击Next,输入名称为CustomCell,选择好位置:

单击Create,这样就创建了CustomCell.xib。

5、打开CustomCell.xib,拖一个Table View Cell控件到面板上:

选中新加的控件,打开Identity Inspector,选择Class为CustomCell;然后打开Size Inspector,调整高度为60。

6、向新加的Table View Cell添加控件:拖放一个ImageView控件到左边,并设置大小为50×50。然后在ImageView右边添加三个Label,设置标签字号,最上边的是14,其余两个是12:

接下来向CustomCell.h添加Outlet映射,将ImageView与三个Label建立映射,名称分别为imageView、nameLabel、decLabel以及locLable,分别表示头像、昵称、个性签名,地点。

选中Table View Cell,打开Attribute Inspector,将Identifier设置为CustomCellIdentifier:

为了充分使用这些标签,还要自己创建一些数据,存在plist文件中,后边会做。

7、打开CustomCell.h,添加属性:


@property (copy, nonatomic) UIImage *image;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *dec;
@property (copy, nonatomic) NSString *loc;

8、打开CustomCell.m,向其中添加代码:

 

8.1 在@implementation下面添加代码:


@synthesize image;
@synthesize name;
@synthesize dec;
@synthesize loc;

 

8.2 在@end之前添加代码:

- (void)setImage:(UIImage *)img {
    if (![img isEqual:image]) {
        image = [img copy];
        self.imageView.image = image;
    }
}

-(void)setName:(NSString *)n {
    if (![n isEqualToString:name]) {
        name = [n copy];
        self.nameLabel.text = name;
    }
}

-(void)setDec:(NSString *)d {
    if (![d isEqualToString:dec]) {
        dec = [d copy];
        self.decLabel.text = dec;
    }
}

-(void)setLoc:(NSString *)l {
    if (![l isEqualToString:loc]) {
        loc = [l copy];
        self.locLabel.text = loc;
    }
}


这相当于重写了各个set函数,从而当执行赋值操作时,会执行我们自己写的函数。

好了,现在自己定义的Cell已经可以使用了。

不过在此之前,我们先新建一个plist,用于存储想要显示的数据。建立plist文件的方法前面的文章有提到。我们建好一个friendsInfo.plist,往其中添加数据如下:

注意每个节点类型选择。

9、打开ViewController.xib,拖一个Table View到视图上,并将Delegate和DataSource都指向File’ Owner,就像上一篇文章介绍的一样。

10、打开ViewController.h,向其中添加代码:


#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *dataList;
@property (strong, nonatomic) NSArray *imageList;
@end


 

11、打开ViewController.m,添加代码:

11.1 在首部添加:


#import "CustomCell.h"


 

11.2 在@implementation后面添加代码:


@synthesize dataList;
@synthesize imageList;


 

11.3 在viewDidLoad方法中添加代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //加载plist文件的数据和图片
    NSBundle *bundle = [NSBundle mainBundle];
    NSURL *plistURL = [bundle URLForResource:@"friendsInfo" withExtension:@"plist"];
    
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
    
    NSMutableArray *tmpDataArray = [[NSMutableArray alloc] init];
    NSMutableArray *tmpImageArray = [[NSMutableArray alloc] init];
    for (int i=0; i<[dictionary count]; i++) {
        NSString *key = [[NSString alloc] initWithFormat:@"%i", i+1];
        NSDictionary *tmpDic = [dictionary objectForKey:key];
        [tmpDataArray addObject:tmpDic];
        
        NSString *imageUrl = [[NSString alloc] initWithFormat:@"%i.png", i+1];
        UIImage *image = [UIImage imageNamed:imageUrl];
        [tmpImageArray addObject:image];
    }
    self.dataList = [tmpDataArray copy];
    self.imageList = [tmpImageArray copy];
}

 

11.4 在ViewDidUnload方法中添加代码:


self.dataList = nil;
self.imageList = nil;


 

11.5 在@end之前添加代码:


#pragma mark -
#pragma mark Table Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
    
    static BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];
        nibsRegistered = YES;
    }
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
 
    
    NSUInteger row = [indexPath row];
    NSDictionary *rowData = [self.dataList objectAtIndex:row];
    
    cell.name = [rowData objectForKey:@"name"];
    cell.dec = [rowData objectForKey:@"dec"];
    cell.loc = [rowData objectForKey:@"loc"];
    cell.image = [imageList objectAtIndex:row];
     
    return cell;
}

#pragma mark Table Delegate Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0;
}

- (NSIndexPath *)tableView:(UITableView *)tableView 
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    return nil;
}


 

12、运行:


 

标签:UITableViewCell,tableView,CustomCell,self,NSString,添加,UITableView,copy,自定义
From: https://blog.51cto.com/u_8895844/6270324

相关文章

  • uniapp 自定义顶部导航
    <uni-nav-bardark:fixed="true"shadowcolor="#333"background-color="#f6f6f6"status-barleft-icon="left"left-text="返回"title="识别结果"@clickLeft="goback">......
  • layer.load 自定义加载
    //layuiload默认加载functionlayerload(){layer.load(0,{content:'正在努力加载中,请稍等',shade:[0.5,'#000'],//0.4为透明度,#000为颜色offset:['45%','40%'],//位置success:function(layero){......
  • c++自定义工具类的定义和使用
    classlog_work{private:intlog_id_=1;intlog_level_;qnx_slog2()=default;virtual~qnx_slog2(){uninit();}public:inlinestaticlog_work&get_log(){staticqnx_slog2slog2_instance;returnslog2_instance;}......
  • c++模版多参数的递归用法--自定义log
    #include<iostream>#include<sstream>#include<string>#include<tuple>#include<type_traits>template<typenameT>voidprint_impl(std::ostringstream&os,constchar*format,T&&arg){while(*form......
  • 自定义信息提示框dialog.js
    varowner;functiongetOwner(){ if(owner) returnowner; varowner=window; try{ if(top.document.domain==window.document.domain){ if(top.length>1) owner2=top[0]; else owner=top; } }catch(ex){ while(owner.p......
  • uniapp自定义开发一个文本输入框
    开发component中的一个input标签一、在原来的模块上面创建一个新的类TestComponent1.新建TestComponent2.配置json文件二、uniapp准备工作1.在uniapp中写一下刚刚创建的输入框2.打包导出资源3.资源替换复制刚刚生成的本地资源文件夹到AndroidStudio项目中......
  • wordpress 为自定义类型文章新增自定义字段
    wordpress强大之处在于有很强的可自定义性,使得插件、主题的开发变得及其便利。就拿我们今天要说的自定义文章添加自定义字段来说,就很便捷。        比如我们要录入一个客户信息到wordpress中,那么需要的字段可不仅仅是什么标题、内容、摘要这么简单了,我们可能需要录入客户......
  • springboot+Prometheus+grafana 实现自定义监控(请求数、响应时间、JVM性能)
    自定义监控1.SpringBoot工程集成Micrometer1.1引入依赖1.2配置1.3监控jvm信息1.4创建自定义监控1.5添加具体业务代码监控2.集成Prometheus2.1安装2.2集成配置3.使用GrafanaDashboard展示监控项3.1安装grafana3.2配置prometheus数据源3.3增加jvm面板3.4配置业务接口监控面板......
  • 百度地图绘制地区的棱柱效果-定位-自定义点-文本标记-信息弹窗
    @目录百度地图webgl使用自定义地图样式地区镂面棱柱效果绘制点信息以及信息弹窗百度地图webgl使用在项目的index.html中引入<scripttype="text/javascript"src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=你的AK秘钥"></script>注意,百度webgl的引入和百度地图的引入......
  • Android自定义Dialog(zhuang)
    Android自定义Dialog这段时间在做一个项目,需要使用到自定义Dialog,先在网上找了一下资料,发现还是有很多没有讲清楚的,在此给出一个Demo,一来可以方便广大码农,二来也可以方便自己,以备不时之需。。。先来一张图吧,很简单,只有一个Activity,当点击Button的时候就弹出这个自定义的Dialo......