UITableViewCell drawInRect 在iOS7中失败

来源:互联网 发布:知乎论坛特点 编辑:程序博客网 时间:2024/06/04 20:05

You shouldn't use UITableViewCell's drawRect method to perform custom drawing. The proper way to do it is to create a custom UIView and add it as a subview of your cell (as a subview of thecontentView property). You can add the drawing code to this custom view and everything will work fine.

As others said, don't use UITableViewCell's drawRect selector directly. By doing that, you're relying on implementation details of UITableViewCell, and Apple made no guarantee that such behaviour won't break in future versions, just as it did in iOS 7... Instead, create a custom UIView subclass, and add it as a subview to the UITableViewCell's contentView, like this:

@implementation CustomTableViewCell- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];    if (self) {        [self.contentView addSubview:[[CustomContentView alloc]initWithFrame:self.contentView.bounds]];    }    return self;}@end

And the CustomContentView:

@implementation CustomContentView- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        self.backgroundColor = [UIColor clearColor];    }    return self;}- (void)drawRect:(CGRect)rect{    NSDictionary * attributes = @{                                  NSFontAttributeName : [UIFont fontWithName:@"Helvetica-bold" size:12],                                  NSForegroundColorAttributeName : [UIColor blackColor]                                  };    [@"I <3 iOS 7" drawInRect:rect withAttributes:attributes];}@end

Works like charm!



0 0
原创粉丝点击