iOS经验4:自定义TableViewCell应用代码例子过程 时间戳

本文主要是介绍iOS经验4:自定义TableViewCell应用代码例子过程 时间戳,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

不用,镔哥多说了,TAbleView在工程项目应用得应该是最多的,但是系统自带的不能满足我的需求,所以在做项目的时候一般都要自定义UITableViewCell来实现我们的目的:

下面首先我把自己的项目的一个代码做为例子介绍:

//

//  RecordTableViewCell.h

// 自定义一个商品历史纪录

//  Created by bin on 14/10/31.

//  Copyright (c) 2014 mac. All rights reserved.

//


#import <UIKit/UIKit.h>

@interface RecordTableViewCell : UITableViewCell

@property (nonatomic, strong) UILabel * timeLable;//时间

@property (nonatomic, strong) UILabel * IDLabel;//ID号

@property (nonatomic, strong) UILabel * numberLabel;//购买数量


- (void)getDataByDictionary:(NSDictionary *)dic;


@end


//  RecordTableViewCell.m

//

//  Created by bin on 14/10/31.

//  Copyright (c) 2014 mac. All rights reserved.

//


#import "RecordTableViewCell.h"


#define BACKCOLOR [UIColor cyanColor]


@implementation RecordTableViewCell


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        

        self.timeLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 120, 20)];

        _timeLable.font = [UIFont systemFontOfSize:12];

        _timeLable.backgroundColor = BACKCOLOR;

        [self addSubview:_timeLable];

        

        self.IDLabel = [[UILabel alloc] initWithFrame:CGRectMake(_timeLable.right, _timeLable.top, 80, _timeLable.height)];

        _IDLabel.backgroundColor = BACKCOLOR;

        _IDLabel.textAlignment = NSTextAlignmentCenter;

        [self addSubview:_IDLabel];

        

        self.numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(_IDLabel.right, _IDLabel.top, 110, _IDLabel.height)];

        _numberLabel.backgroundColor = BACKCOLOR;

        _numberLabel.font = [UIFont systemFontOfSize:14];

        _numberLabel.tintColor = [UIColor colorWithRed:165 green:3 blue:16 alpha:1];

        [self addSubview:_numberLabel];

        

    }

    return self;

}

//购买的时间

- (void)getDataByDictionary:(NSDictionary *)dic

{

    self.timeLable.text = [self getTImeBytimestampString:[dic objectForKey:@"joinTime"]];

    self.IDLabel.text = [dic objectForKey:@"joinerPhone"];

    self.numberLabel.text = [NSString stringWithFormat:@"购买了%@人次", [dic objectForKey:@"joinCount"]];

}


//根据时间戳返回时间

- (NSString *)getTImeBytimestampString:(NSString *)timstampStr

{

    NSDate * date = [NSDate dateWithTimeIntervalSince1970:[timstampStr longLongValue] / 1000];

    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

    NSString * str = [NSString stringWithFormat:@"%@", [formatter stringFromDate:date]];

    return str;

}

//===========================================使用===============

在应用的窗口中就直接这样写就可以了

#pragma mark - UITabelViewDatasource

- (RecordTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    RecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];

    NSDictionary * dic = [_dataArray objectAtIndex:indexPath.row];

    [cell getDataByDictionary:dic];

    return cell;

}


//===========下面就具体介绍解析一下,让大家更容易明白
很多时候,我们需要自定义UITableView来满足我们的特殊要求。这时候,关于UITableView和cell的自定义和技巧太多了,就需要不断的总结和归纳。
1.添加自定义的Cell
这个问题已经涉及过,但是,这里要说的主要是两种方法的比较!
因为,我经常发现有两种方式:

1.xib方式
这种方式,也就是说,为自定义的UITableViewCell类添加一个xib的文件。并且让两者关联。
这时候,写法为:

// 返回cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    

    static NSString *CellIdentifier = @"MyCell";

    // 自定义cell

    MyCell *cell = (MyCell *)[tableVie dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil){

        // 这种方式,将会查找响应的xib文件,将不会调用initWithStyle方法

        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:niloptions:nil];

        cell = [array objectAtIndex:0];

    }

这种方式,是读取了xib文件,所以,就直接按照响应的xib中的布局,布局好了,并不会调用相应的initWithStyle方法。


2.调用initWithStyle方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"MyCell";

    // 自定义cell

    MyCell *cell = (MyCell *)[tableVie dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil){

        // 这种方式,将会调用cell中的initWithStyle方法

        cell = [[[MyCell alloc] initWithStyle:UITableViewCellSelectionStyleGray reuseIdentifier:CellIdentifier] autorelease];

    }

    return cell;

    

}


这种方式,会调用相应Cell类的initWithStyle方法。

那么,什么时候,用那种方式呢?
我的理解是:
当,cell比较简单时,可以添加相应的xib文件,进行关联;当cell比较复杂时,就直接用纯代码的方式(不创建相应的xib文件)。
我发现,我还是喜欢用纯代码的方式来写,因为,扩展性好,尤其当cell元素复杂甚至带有动画效果的时候,用xib反而很难控制,或者根本无法控制。
我建议用纯代码的方式!


2.设置cell的setAccessoryView属性

主要用在:在右边添加一个自定义的按钮,或者子视图。
setAccessoryView设置一个按钮。

cell.accessoryType = UITableViewCellAccessoryNone;

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    

    [button setFrame:CGRectMake(0.00.05557)];

    [button setImage:[UIImage imageNamed:@"tap_normal.png"]forState:UIControlStateNormal];

    [button setImage:[UIImage imageNamed:@"tap_highlight.png"]forState:UIControlStateHighlighted];

    [button setTag:indexPath.row];

    [button addTarget:self action:@selector(doClickPlaybillAction:event:) forControlEvents:UIControlEventTouchUpInside];


    [button setBackgroundColor:[UIColor clearColor]];

    [cell setAccessoryView:button];


    return cell;


通过观察属性定义:

@property(nonatomic) UITableViewCellAccessoryType   accessoryType;              

@property(nonatomic,retain) UIView                 *accessoryView;              

@property(nonatomic) UITableViewCellAccessoryType   editingAccessoryType;       

@property(nonatomic,retain) UIView                 *editingAccessoryView; 

可见,accessoryView属性需要的参数为UIView,所以,可以很方便的自定义。当然还有editingAccessoryView,可以进行自定义修改时的UIView。

根据用户点击的按钮,找到相应的Cell

- (void) performExpand:(id)paramSender{


    UITableViewCell *ownerCell = (UITableViewCell*)[paramSender superview];// 获得父视图,即TableViewCell

    if (ownerCell != nil){


        NSIndexPath *ownerCellIndexPath = [self.myTableView indexPathForCell:ownerCell];

        NSLog(@"Accessory in index path is tapped. Index path = %@", ownerCellIndexPath);

        

    }

}


3.自定义cell选择时的样式。


通过,上面一步,我们为Cell添加了一个自定义的按钮。

也许就会遇到这么一个纠结的情况,当点击UITableViewCell高亮时,其子视图中不该高亮的对象(比如说自定义的那个按钮)也高亮了。


比如:

正确方式:我们需要cell被选中时,按钮不应该也被高亮显示。如:




错误方式:但是,cell被选中时,按钮却也高亮显示了。如:




要解决该方法,可以这样:

 

 

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{

    [super setHighlighted:highlighted animated:animated];

    

    if(highlighted) {

        [(UIButton *)self.accessoryView setHighlighted:NO];

    }

}


 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{

    [super setSelected:selected animated:animated];

    if(selected) {

        [(UIButton *)self.accessoryView setHighlighted:NO];

    }

}


这样,问题时解决了,那如果我们再深一层次,发问一下:

为什么UITableViewCell被选中时,UITableViewCell中的其他元素也会被高亮显示呢?

因为UITableViewCell为选中状态时,UITableViewCellselectedBackgroundView当作一个子视图来添加;

selectedBackgroundView被添加在UITableViewCellbackgroundView之上,或者所有其它视图之下。

当调用setSelected: animated:这一方法时,会导致selectedBackgroundView以一个alpha消化的状态来出现和消失。

还应该注意:

UITableViewCellselectionStyleUITableViewCellSelectionStyleNone时,selectedBackgroundView将不起作用。





4.为UITableViewCell添加自定义背景

有时候,我们要为UITableViewCell自定义的类的每个cell添加自定义的背景图片。
有很多方法:
1.在自定义的UITableViewCell类的initWithStyle方法中,添加如下代码:

// 设置背景

        UIImageView *bgImage=[[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,320, 57)] autorelease];

        [bgImage setImage: [UIImage imageNamed:@"table_live_bg.png"]];

        [self setBackgroundView:bgImage];


2.使用setBackgroundImageByName方法或者setBackgroundImage方法

[self setBackgroundImageByName:@"table_live_bg.png"];

[self setBackgroundImage:[UIImage imageNamed:@"table_live_bg.png"]];

这种方法,要注意的时,设置的图片大小应该与cell大小相同

3.设置cell的contentView,用insertSubview方法

[self.contentView insertSubview:messageBackgroundViewbelowSubview:self.textLabel];

        

 self.selectionStyle = UITableViewCellSelectionStyleNone;


这三种方式,都在initWithStyle方法中设置。

5.设置删除Cell时的自定义文本

//定制Delete字符串,添加函数 返回要显示的字符串

-(NSString *)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{

    return @"删除";

}



希望对大家有所帮助!


这篇关于iOS经验4:自定义TableViewCell应用代码例子过程 时间戳的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/294184

相关文章

利用c++判断水仙花数并输出示例代码

《利用c++判断水仙花数并输出示例代码》水仙花数是指一个三位数,其各位数字的立方和恰好等于该数本身,:本文主要介绍利用c++判断水仙花数并输出的相关资料,文中通过代码介绍的非常详细,需要的朋友可以... 以下是使用C++实现的相同逻辑代码:#include <IOStream>#include <vec

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

SpringBoo WebFlux+MongoDB实现非阻塞API过程

《SpringBooWebFlux+MongoDB实现非阻塞API过程》本文介绍了如何使用SpringBootWebFlux和MongoDB实现非阻塞API,通过响应式编程提高系统的吞吐量和响应性能... 目录一、引言二、响应式编程基础2.1 响应式编程概念2.2 响应式编程的优势2.3 响应式编程相关技术

SpringBoot的全局异常拦截实践过程

《SpringBoot的全局异常拦截实践过程》SpringBoot中使用@ControllerAdvice和@ExceptionHandler实现全局异常拦截,@RestControllerAdvic... 目录@RestControllerAdvice@ResponseStatus(...)@Except

Java 接口定义变量的示例代码

《Java接口定义变量的示例代码》文章介绍了Java接口中的变量和方法,接口中的变量必须是publicstaticfinal的,用于定义常量,而方法默认是publicabstract的,必须由实现类... 在 Java 中,接口是一种抽象类型,用于定义类必须实现的方法。接口可以包含常量和方法,但不能包含实例

线程池ThreadPoolExecutor应用过程

《线程池ThreadPoolExecutor应用过程》:本文主要介绍如何使用ThreadPoolExecutor创建线程池,包括其构造方法、常用方法、参数校验以及如何选择合适的拒绝策略,文章还讨论... 目录ThreadPoolExecutor构造说明及常用方法为什么强制要求使用ThreadPoolExec

自定义注解SpringBoot防重复提交AOP方法详解

《自定义注解SpringBoot防重复提交AOP方法详解》该文章描述了一个防止重复提交的流程,通过HttpServletRequest对象获取请求信息,生成唯一标识,使用Redis分布式锁判断请求是否... 目录防重复提交流程引入依赖properties配置自定义注解切面Redis工具类controller

mysql_mcp_server部署及应用实践案例

《mysql_mcp_server部署及应用实践案例》文章介绍了在CentOS7.5环境下部署MySQL_mcp_server的步骤,包括服务安装、配置和启动,还提供了一个基于Dify工作流的应用案例... 目录mysql_mcp_server部署及应用案例1. 服务安装1.1. 下载源码1.2. 创建独立

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

mybatis-plus分表实现案例(附示例代码)

《mybatis-plus分表实现案例(附示例代码)》MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生,:本文主要介绍my... 目录文档说明数据库水平分表思路1. 为什么要水平分表2. 核心设计要点3.基于数据库水平分表注意事项示例