设置IUTableViewCell子类子视图的alpha

时间:2012-02-04 23:53:40

标签: ios uitableview

我有一个UITableViewCell的子类。我正在尝试调整whiteLine子视图的alpha,但只有在滚动到屏幕外单元格时,alpha才会生效。初始批whiteLine个子视图的alpha值为1.0。

以下是我设置表格单元格的方法:

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

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

    // Configure the cell...
    [cell rowIsOdd:(indexPath.row%2 ? NO : YES)];

    return cell;
}

以下是我设置whiteLine并在表格单元子类中更改其alpha的方法:

- (void)drawRect:(CGRect)rect
{
    self.whiteLine = [[UIView alloc] initWithFrame:CGRectMake(0.0, self.frame.size.height-1.0, self.frame.size.width, 1.0)];
    self.whiteLine.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.whiteLine];
}

- (void)rowIsOdd:(BOOL)isOdd
{
    self.whiteLine.alpha = (isOdd ? 0.7 : 0.3);
}

问题是我正在使用属性吗?我不知道什么时候使用属性。这肯定不是可以在本课程之外访问的属性。

2 个答案:

答案 0 :(得分:0)

我明白了。我需要在awakeFromNib而不是drawRect设置视图。

答案 1 :(得分:0)

您可能希望将whiteLine子视图初始化移至initWithStyle:reusedIdentifier:目前,您在实例化之前设置了alpha。此外,每次调用drawRect:时都会创建一个新视图,这肯定是禁忌的。

我目前不在编译器中,但是这样的事情可以解决你的问题:

请注意,我还将自动释放调用添加到了whiteLine子视图中(我假设它是一个保留属性)。如果您对Cocoa Memory Management不满意,可能需要考虑使用ARC。否则,我建议您重新阅读Apple's Memory Management指南,以及可能非常好的Google Objective-C Code Style Guide

在BaseCell.m中:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)identifier {
    self = [super initWithStyle:style reuseIdentifier:identifier];
    if (self) {
        self.whiteLine = [[[UIView alloc] initWithFrame:CGRectMake(0.0,  self.frame.size.height-1.0, self.frame.size.width, 1.0)] autorelease];
        self.whiteLine.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.whiteLine];
    }
    return self;
}

- (void)dealloc {
    self.whiteLine = nil;
    [super dealloc];
}

- (void)rowIsOdd:(BOOL)isOdd
{
    self.whiteLine.alpha = (isOdd ? 0.7 : 0.3);
}