UITableViewCell显示不正确的基于alpha的背景颜色

时间:2010-02-18 19:16:23

标签: iphone objective-c cocoa xcode

我有一个UITableViewCell,带有UITableViewStyleGrouped样式,我想改变单元格的背景颜色。

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)ip {
    // Do cell creation stuff ...

    cell.backgroundColor = 
      [UIColor colorWithRed:255.0/255.0 green:243.0/255.0 blue:175.0/255.0 alpha:0.50];
}

问题是,这在UITableViewStyleGrouped的网格上无法正常显示;我在UITableViewStylePlain上使用相同的颜色,并且显示正确。我正在为OS 3.0开发,并在设置背景颜色时阅读了multiple posts。我可以设置它没有正确设置的颜色!我错过了什么?

Incorrect yellow background with Alpha Correct yellow background with Alpha

2 个答案:

答案 0 :(得分:1)

您必须在单元格创建/重用逻辑中执行某些操作才能更改默认行为。从头开始项目并实现此代码对我有用:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

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

    // Configure the cell.
    cell.backgroundColor = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:1.0];

    return cell;
}

如果您需要更复杂的内容,请仔细检查documentation

另外,由于两种不同风格的桌面背景颜色不同,颜色会发生变化吗? UITableViewStylePlain tableView具有默认的白色背景。 UITableViewStyleGrouped tableView将具有灰色背景。由于您将alpha设置为0.5,因此它将叠加到两个不同的颜色背景上,并为您提供色彩偏移。

答案 1 :(得分:0)

我确定不支持此方法,但确实有效。关闭xcode,在文本编辑器(如vi)中打开.xib或.storyboard文件。找到表的XML并更改单元格颜色。例如,以下是默认白表单元格的原始部分:

<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" indicatorStyle="black" dataMode="prototypes" style="plain" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="k63-au-YAF">
  <rect key="frame" x="0.0" y="0.0" width="320" height="480"/>
  <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
  <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
  <prototypes>

查找并更改颜色标记。这是一个包含原始帖子颜色的示例:

<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" indicatorStyle="black" dataMode="prototypes" style="plain" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="k63-au-YAF">
  <rect key="frame" x="0.0" y="0.0" width="320" height="480"/>
  <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
  <color key="backgroundColor" red="1.0" green="0.95294117647059" blue="0.68627450980392" alpha="0.5" colorSpace="calibratedRGB"/>
  <prototypes>

再次打开xcode,您的单元格颜色已更新。

注意:对于颜色代码,243/255 = 0.95294117647059(绿色),175/255 = 0.68627450980392(红色)等。