概述
UITableViewCell是UITableView的信息展示单元,在药品指南中大量用到,总结一下用法,以便以后简单的使用。
基本属性
UITableViewCell默认自带一个UIImageView,UILabel。这2个一般不能满足我们的需求,经常需要我们自定义cell,
自定义通过
[cell.contentView addSubview:diseaseNameLabel];
类似方法可以添加到cell中。
UITableViewCell的复用
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
这样可以复用cell,减少内存开支。
但是如果你对每个cell做了特殊的处理,。
if (index.row == 0)
{
//do something,,,
}
要加上index.row的值不等于0的处理,因为是复用的,如果不做处理,会吧index.row == 0的效果也会出现的。
选中效果
UITableViewCell自带3中选中效果
typedef enum {
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray
} UITableViewCellSelectionStyle;
但是仍提供了自定义选中效果的方法。
// Default is nil for cells in UITableViewStylePlain, and non-nil for UITableViewStyleGrouped. The 'selectedBackgroundView' will be added as a subview directly above the backgroundView if not nil, or behind all other views. It is added as a subview only when the cell is selected. Calling -setSelected:animated: will cause the 'selectedBackgroundView' to animate in and out with an alpha fade.
@property(nonatomic,retain) UIView *selectedBackgroundView;
这个是cell在选中是背景的实体,我们可以自定义之。
accessoryType
cell的accessoryType
typedef enum {
UITableViewCellAccessoryNone, // don't show any accessory view
UITableViewCellAccessoryDisclosureIndicator, // regular chevron. doesn't track
UITableViewCellAccessoryDetailDisclosureButton, // blue button w/ chevron. tracks
UITableViewCellAccessoryCheckmark // checkmark. doesn't track
} UITableViewCellAccessoryType;
同样也提供了自定义的方法
@property(nonatomic,retain) UIView *accessoryView; // if set, use custom view. ignore accessoryType. tracks if enabled can calls accessory action
在xib中定义cell
在tableview的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
中添加代码
{
NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
cell = [array objectAtIndex:0];
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
}
loadNibNamed的参数是cell的xib文件名。然后我们可以直接使用我们自定义的cell。
自定义背景
UIImageView *imageView = [[UIImageView alloc] initWithFrame:cell.frame];
[imageView setImage:[UIImage imageNamed:@"test.png"]];
cell.backgroundView = imageView;
可以改变cell的背景。