【问题标题】:UITableView and CALayer confusionUITableView 和 CALayer 混淆
【发布时间】:2011-04-08 14:35:03
【问题描述】:

我有一个非常简单的UITableViewCell 子类。 MyTableViewCell.h:

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>


@interface MyTableViewCell : UITableViewCell {
    CALayer *backgroundLayer;
}

@end

MyTableViewCell.m:

#import "MyTableViewCell.h"
#import <QuartzCore/QuartzCore.h>


@implementation MyTableViewCell


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        backgroundLayer = [[CALayer alloc] init];
        [backgroundLayer setBackgroundColor:[[UIColor yellowColor] CGColor]];
        [[self layer] addSublayer:backgroundLayer];
    }
    return self;
}


- (void)layoutSublayersOfLayer:(CALayer *)layer {
    [backgroundLayer setFrame:[layer frame]];
    [super layoutSublayersOfLayer:layer];
}


- (void)dealloc {
    [backgroundLayer release];
    [super dealloc];
}


@end

奇怪的是,结果如下:。

谁能解释一下?!为什么图层不是在所有单元格中绘制,而是每隔一个单元格绘制一次?

编辑:这是我的tableView:cellForRowAtIndexPath: 方法:

static NSString *reuseIdentifier = @"cellReuseIdentifier";

MyTableViewCell *cell = (MyTableViewCell *)[aTableView dequeueReusableCellWithIdentifier:reuseIdentifier];

if (cell == nil)
    cell = [[[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease];

return cell;

【问题讨论】:

  • 它可能是你的 tableView:cellForRowAtIndexPath: 中的东西,你能发布你对这个方法的实现吗?
  • 想不出代码有什么明显错误。但请注意,layer 方法的引用说它返回“初始化的 CALayer 对象,如果初始化不成功,则返回 nil”。也许检查它没有返回零。
  • @jjoelson:我也没有。当我滚动时,一切都搞砸了,大多数单元格完全消失了……也许这是苹果代码中的错误?编辑:它永远不会返回 nil。
  • 其实可能是内存管理问题。您应该保留 CALayer 对象,因为您将其保存在 ivar 中(当然也可以在 dealloc 中释放它)。我不确定这是否是问题,因为将其添加为子层应该可以防止它被释放,但值得一试。
  • 另外,您可能想尝试在初始化方法中设置图层的框架。

标签: iphone objective-c uitableview calayer


【解决方案1】:

使用这个方法成功了:

- (void)layoutSublayersOfLayer:(CALayer *)layer {
    CGRect frame = [layer frame];
    frame.origin = CGPointZero;
    [backgroundLayer setFrame:frame];
    [super layoutSublayersOfLayer:layer];
}

【讨论】:

    【解决方案2】:

    虽然与您的问题无关,但您应该将图层添加到 [self.contentView 图层]。否则删除滑动等编辑功能将无法正确呈现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-25
      • 2013-08-24
      • 2013-01-04
      • 1970-01-01
      • 2016-07-11
      • 2021-04-10
      • 2021-11-06
      • 2011-12-04
      相关资源
      最近更新 更多