UITableViewCell drawInRect iOS7

Luk*_*uke 4 objective-c uitableview drawrect ios7

嗨,我正在尝试使用以下代码在iOS 7中的UITableViewCell中绘制字符串

-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
CGRect playerNameRect = CGRectMake(0, kCellY, kPlayerNameSpace, kCellHeight);

NSDictionary*dictonary = [NSDictionary
                          dictionaryWithObjectsAndKeys:
                          [UIColor hmDarkGreyColor], NSForegroundColorAttributeName,
                          kFont, NSFontAttributeName,
                          nil];

[self.playerName drawInRect:playerNameRect withAttributes:dictonary];

}
Run Code Online (Sandbox Code Playgroud)

但是我无法显示任何内容... self.playerName不是nil,并且playerNameRect是正确的.

我以前使用以下代码执行相同的操作,但最近在iOS 7中已弃用

        [self.playerName drawInRect:playerNameRect withFont:kFont lineBreakMode:NSLineBreakByTruncatingTail alignment:NSTextAlignmentCenter];
Run Code Online (Sandbox Code Playgroud)

同样奇怪的是我无法在UITableViewCell上的drawRect中绘制任何内容...当我在一个UIView上使用drawingRect时,不推荐使用的代码可以正常工作.

Lui*_*ien 11

你不应该使用UITableViewCelldrawRect方法来执行自定义绘图.正确的方法是创建一个自定义UIView并将其添加为您的单元格的子视图(作为contentView属性的子视图).您可以将绘图代码添加到此自定义视图中,一切都可以正常工作.

希望这可以帮助!

查看这些帖子:

表格视图单元格自定义图纸1

表格视图单元格自定义图纸2

表格视图单元格自定义图纸3


Tam*_*ola 7

正如其他人所说,不要直接使用UITableViewCell的drawRect选择器.通过这样做,你依赖于UITableViewCell的实现细节,并且Apple不保证这样的行为在未来的版本中不会破坏,就像在iOS 7中那样...而是创建一个自定义的UIView子类,并添加它作为UITableViewCell的contentView的子视图,如下所示:

@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
Run Code Online (Sandbox Code Playgroud)

和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
Run Code Online (Sandbox Code Playgroud)

像魅力一样工作!