我们定制TableViewCell的时候,往往根据个性需求不同,会在cell上加不同的内容。在cell上添加子视图的方式有两种。例如我在cell上加一个Label:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:thirdIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:thirdIdentifier] ;
//北京市
CGFloat widths = SCREEN_WIDTH-130;
CGFloat lefts = 100;
if (is_ios6) {
lefts = 30;
widths = SCREEN_WIDTH - 80;
}
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(lefts,0, widths, cell.height)];
tempLabel.backgroundColor = [UIColor clearColor];
tempLabel.tag = indexPath.row+100;
tempLabel.font = [UIFont systemFontOfSize:14.0f];
tempLabel.textAlignment = NSTextAlignmentRight;
tempLabel.text = _remindArray[indexPath.row];
[cell.contentView addSubview:tempLabel];//建议使用
// [cell addSubview:tempLabel];
加子视图的两种方式,一种是直接加在cell上,另一种是直接加在cell.contentView上。之前我为了方便一直都直接加在cell上,并认为他们并无区别。但是直到今天我遇到一个奇怪的问题,引起了我的重视。当我想要找到我添加到cell上的某个特定的子视图时,通过以下方法。
//根据选中的行数来改变对应的cell的内容
- (void)changeLabelTextWithCode:(NSInteger)code WithTextLabel:(NSString *)text WithPickViewText:(NSString *)rowText
//rowText表示要更换的内容
{
//获取到当前的cell
UITableViewCell *cell = [self.orderLevelView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:code-1 inSection:0]];
for (UIView *views in cell.subviews) {
if ([views isKindOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)views;
if (![label.text isEqualToString:text]) {
label.text = rowText;
}
}
}
}
但是发现通过cell.subviews根本找不到我添加的label,经研究发现,把label加在cell.contentView上,查找时通过cell.contentView.subviews就可以完美的解决这个问题。看来写代码的时候真不能想当然的认为简单的就是最好的。
(ios8系统比较强大,可以自己分辨出加在cell上的子视图。可以不用加在cell.contentView上,但是目前大家都还要兼顾ios7甚至6系统。所以建议还是加在cell.contentView上吧)