Ami*_*ela 35 iphone cocoa-touch uitableview
我正在开发一个iPhone应用程序,在我的表视图中我想要Cell Selection Style的自定义颜色,我读了UITableViewCell类参考但是只有三个常量定义为Selection样式(Blue,Gray,None).我看到一个应用程序使用的颜色与参考中定义的颜色不同.
我们如何使用参考中定义的颜色以外的颜色?
提前致谢.
Mat*_*her 64
设置选择的最佳方法是selectedBackgroundView在构造单元格时设置单元格.
即
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SelectedCellBackground.png"]] autorelease];
}
// configure the cell
}
Run Code Online (Sandbox Code Playgroud)
使用的图像应该有一个很好的渐变(如默认选择).如果你只想要一个平面颜色,你可以使用UIView而不是a UIImageView并设置backgroundColor你想要的颜色.
选择行后,将自动应用此背景.
小智 24
设置selectedBackgroundView似乎当没有任何效果cell.selectionStyle设置为UITableViewCellSelectionStyleNone.当我没有设置样式时,只使用默认的灰色.
使用第一个将自定义UIView插入单元格的建议会操作单元格,但只有在完成所选操作后才会显示单元格,但是因为我正在推送到新视图.如何在单元格中选择要在所选操作开始之前显示的视图?
Wil*_*ter 13
如果您已经为UITableViewCell创建子类,则可以通过覆盖以下内容来自定义单元格的各种元素:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
Run Code Online (Sandbox Code Playgroud)
编辑iOS7:正如Sasho所说,你也需要
cell.selectionStyle = UITableViewCellSelectionStyleNone
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的一些,我实际上更喜欢创建自己的UITableViewCell子类,然后覆盖touchesBegan/touchesCancelled/touchesEnded方法.要执行此操作,请忽略单元格上的所有selectedBackgroundView和highlightedColor属性,而只需在调用上述方法之一时手动设置这些颜色.例如,如果要将单元格设置为具有红色文本的绿色背景,请尝试此操作(在自定义单元格子类中):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//Set backgorund
self.backgroundColor = [UIColor themeBlue];
//Set text
self.textLabel.textColor = [UIColor themeWhite];
//Call super
[super touchesBegan:touches withEvent:event];
}
Run Code Online (Sandbox Code Playgroud)
请注意,为此,您需要设置:
self.selectionStyle = UITableViewCellSelectionStyleNone;
Run Code Online (Sandbox Code Playgroud)
否则,您将首先获得当前的选择样式.
编辑:我建议使用touchesCancelled方法恢复原始单元格颜色,但只是忽略touchesEnded方法.