在自定义UITableViewCell中给出UITextField时,单元格被突出显示/选中时正确的文本颜色

问题描述:

我有一个自定义UITableViewCell样式UITableViewCellSelectionStyleBlue。它有一个UITextField在里面。在自定义UITableViewCell中给出UITextField时,单元格被突出显示/选中时正确的文本颜色

每当单元格被突出显示/选择(即具有蓝色背景)时,我想UITextField具有白色,就像内置标签自动执行一样。

当然,这包括确保背景颜色的“白色到蓝色”或“蓝色到白色”褪色动画发生时文本字段的颜色是正确的。

我该如何正确地做到这一点?

我认为最好的办法是使表视图单元格的一个子类,并在此方法重写setSelected:animated:

你会现场的文本颜色更改为你想要什么,这取决于所选标志

动画你只想把一个动画块内:

[UIView animateWithDuration:.3f animations:^{ 
    field.textColor = [UIColor whiteColor]; 
}]; 
+0

这样做的问题是,在实际选择之前的小区经常强调。我想不得不考虑到setHighlighted和setSelected方法的相互作用,我认为... – Enchilada 2012-02-03 18:34:32

+0

绝对的,在苹果指南的某个地方很好地描述了如何选择和突出显示一起工作(谷歌正在失败我,也许它是在书中?),但你需要使用两者来获得完美的解决方案 – wattson12 2012-02-04 13:17:45

由于电池是“自定义”,我相信你已经创建了一个子类。

首先,UITableViewCellSelectionStyleBlue不是UITableViewCellStyle,其选择的风格,因此它不应该在-init方法中使用,但也可以是作为它的值将是相同的,为UITableViewCellStyle

此外,为了在选择时编辑单元格,您需要覆盖方法-setSelected:animated:。此外,您需要将单元格的textField的textColor变量设置为白色,反之亦然,蓝色。

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

    self.textField.textColor = (selected == YES ? [UIColor whiteColor] : [UIColor blueColor]); 

    [super setSelected:selected animated:animated];   

} 

否则,它可能是最好的呼叫在-tableView:didSelectRowAtIndexPath:方法的方法。

- (void) tableView:(UITableView *) _tableView didSelectRowAtIndexPath:(NSIndexPath *) _indexPath { 

    [self rowSelected:_indexPath]; 

} 

- (void) rowSelected:(NSIndexPath *) indexPath { 

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 
    BOOL isSelected = cell.isSelected; 
    [(UITextField *) [cell viewWithTag:kTextFieldTag] setTextColor:(isSelected == YES ? [UIColor whiteColor] : [UIColor blueColor])]; 


} 
+0

这是我的工作! – 2012-02-10 10:17:10

如果您在Interface Builder设计您的自定义单元格,然后给出UITextField在属性检查器默认为黑色“突出”属性。将其设置为白色,文本颜色随着触摸而变化。

//In your .h file 

NSIndexPath * selectedIP;

//in.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell1"; 

    UITableViewCell *cell =(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 


    if (nil ==cell) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    if (indexPath == selectedIP) { 
     textField.textColor = [UIColor whiteColor]; 
    } else{ 
     textField.textColor = [UIColor blackColor]; 
    } 
    [self configureCell:cell atIndexPath:indexPath]; 

    return cell; 
} 


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    NSIndexPath *temp = selectedIP; 
    selectedIP = nil; 
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:temp] withRowAnimation:UITableViewRowAnimationNone]; 
    selectedIP = indexPath; 

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:selectedIP] withRowAnimation:UITableViewRowAnimationNone]; 


}