重用UITableViewCell时缺少子视图

时间:2014-07-25 17:54:58

标签: ios objective-c uitableview parse-platform

我在layoutSubviews上有一个包含以下代码的自定义单元格:

// Separator Inset
UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, 320, 0.5)];
line.backgroundColor = [UIColor blackColor];
[self addSubview:line];

它正确添加了子视图,问题是当我向下滚动并返回子视图时消失。

也许与重复使用细胞有关,但我不确定我错过了什么。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
    static NSString *CellIdentifier = @"ExerciciosCell";
    ExerciciosCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (!cell) {
        cell = [[ExerciciosCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

更新: 在cellForRowAtIndexPath

NSLog(@"subviews: %d", cell.contentView.subviews.count);` 
NSLog(@"%@", cell.contentView.subviews);

结果:

"<UILabel: 0x15dca980; frame = (60 12; 248 21); text = 'Supino Reto Na Maquina'; clipsToBounds = YES; layer = <CALayer: 0x15dab2c0>>",
    "<UITableViewLabel: 0x15dd1880; frame = (60 32; 248 18); text = 'Peso: 50 - 3x10 reps'; clipsToBounds = YES; layer = <CALayer: 0x15dc7410>>",
    "<UIImageView: 0x15e91ff0; frame = (0 60; 320 0.5); userInteractionEnabled = NO; layer = <CALayer: 0x15ecaa80>>",
    "<UIImageView: 0x15dcc730; frame = (5 5; 50 50); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x15db8100>>"

3 个答案:

答案 0 :(得分:3)

layoutSubviews被称为很多次。这不是添加子视图的正确位置。较旧的图像视图正在被较新的图像视图覆盖。

添加子视图的正确位置是init...方法。

答案 1 :(得分:1)

我在自己的应用程序中注意到,如果行的y偏移量与单元格的高度相同,则在滚动时,单元格底部的一条线会消失。如果我把线(像你的一条高0.5线)放在细胞底部0.5点以上,那么它就不会消失。我猜这与表格处理细胞分离器的方式有关,所以我不知道是否有更好的方法来处理它。

答案 2 :(得分:0)

如果出于某种原因想要在layoutSubviews中维护代码:如何在界面中创建属性:

@interface MyTableViewCell ()

@property (nonatomic, strong) UIImageView *line;

@end

然后在您的实施中:

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (!self.line)
    {
        self.line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, 320, 0.5)];
        self.line.backgroundColor = [UIColor blackColor];
        [self addSubview:self.line];
    }
}
相关问题