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

相关文章

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

作业提交过程之HDFSMapReduce

作业提交全过程详解 (1)作业提交 第1步:Client调用job.waitForCompletion方法,向整个集群提交MapReduce作业。 第2步:Client向RM申请一个作业id。 第3步:RM给Client返回该job资源的提交路径和作业id。 第4步:Client提交jar包、切片信息和配置文件到指定的资源提交路径。 第5步:Client提交完资源后,向RM申请运行MrAp

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

hdu1394(线段树点更新的应用)

题意:求一个序列经过一定的操作得到的序列的最小逆序数 这题会用到逆序数的一个性质,在0到n-1这些数字组成的乱序排列,将第一个数字A移到最后一位,得到的逆序数为res-a+(n-a-1) 知道上面的知识点后,可以用暴力来解 代码如下: #include<iostream>#include<algorithm>#include<cstring>#include<stack>#in

zoj3820(树的直径的应用)

题意:在一颗树上找两个点,使得所有点到选择与其更近的一个点的距离的最大值最小。 思路:如果是选择一个点的话,那么点就是直径的中点。现在考虑两个点的情况,先求树的直径,再把直径最中间的边去掉,再求剩下的两个子树中直径的中点。 代码如下: #include <stdio.h>#include <string.h>#include <algorithm>#include <map>#

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来