如何解决选择单元格时 UITableViewCell 子视图消失?
UITableViewCell
选择或突出显示单元格时更改所有子视图的背景颜色,您可以通过覆盖 Tableview
单元格和重置视图背景颜色来解决此setSelected:animated
问题setHighlighted:animated
。
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
UIColor *color = self.yourView.backgroundColor;
[super setSelected:selected animated:animated];
if (selected){
self.yourView.backgroundColor = color;
}
}
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
UIColor *color = self.yourView.backgroundColor;
[super setHighlighted:highlighted animated:animated];
if (highlighted){
self.yourView.backgroundColor = color;
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
let color = yourView.backgroundColor
super.setSelected(selected, animated: animated)
if selected {
yourView.backgroundColor = color
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let color = yourView.backgroundColor
super.setHighlighted(highlighted, animated: animated)
if highlighted {
yourView.backgroundColor = color
}
}
解决方法
我正在实现一个颜色选择器表视图,用户可以在其中选择 10 种颜色(取决于产品)。用户还可以选择其他选项(如硬盘容量,…)。
所有颜色选项都在它们自己的 tableview 部分中。
我想在 textLabel 左侧显示一个小方块,显示实际颜色。
现在我正在添加一个简单的方形 UIView,给它正确的背景颜色,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RMProductAttributesCellID];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:RMProductAttributesCellID] autorelease];
cell.indentationWidth = 44 - 8;
UIView *colorThumb = [[[UIView alloc] initWithFrame:CGRectMake(8,8,28,28)] autorelease];
colorThumb.tag = RMProductAttributesCellColorThumbTag;
colorThumb.hidden = YES;
[cell.contentView addSubview:colorThumb];
}
RMProductAttribute *attr = (RMProductAttribute *)[_product.attributes objectAtIndex:indexPath.section];
RMProductAttributeValue *value = (RMProductAttributeValue *)[attr.values objectAtIndex:indexPath.row];
cell.textLabel.text = value.name;
cell.textLabel.backgroundColor = [UIColor clearColor];
UIView *colorThumb = [cell viewWithTag:RMProductAttributesCellColorThumbTag];
colorThumb.hidden = !attr.isColor;
cell.indentationLevel = (attr.isColor ? 1 : 0);
if (attr.isColor) {
colorThumb.layer.cornerRadius = 6.0;
colorThumb.backgroundColor = value.color;
}
[self updateCell:cell atIndexPath:indexPath];
return cell;
}
这显示没有问题。
我唯一的问题是,当我选择“颜色”行时,在淡入蓝色选择动画期间,我的自定义 UIView (colorThumb)
被隐藏。它在选择/取消选择动画结束后再次可见,但这会产生丑陋的伪影。
我应该怎么做才能纠正这个?我不是在正确的位置插入子视图吗?
(didSelectRowAtIndexPath 没有什么特别之处,我只是将单元格的附件更改为复选框或什么都没有,并取消选择当前的 indexPath)。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。