UITableViewCell drawInRect iOS7

时间:2013-09-19 22:24:56

标签: objective-c uitableview ios7 drawrect

您好我正在尝试使用以下代码在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];

}

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

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

        [self.playerName drawInRect:playerNameRect withFont:kFont lineBreakMode:NSLineBreakByTruncatingTail alignment:NSTextAlignmentCenter];

奇怪的是我无法在UITableViewCell上绘制drawRect ...当我在一个UIView上绘图时,不推荐使用的代码可以正常工作。

4 个答案:

答案 0 :(得分:11)

您不应使用UITableViewCell的{​​{1}}方法来执行自定义绘图。正确的方法是创建自定义drawRect并将其添加为单元格的子视图(作为UIView属性的子视图)。您可以将绘图代码添加到此自定义视图中,一切都可以正常工作。

希望这有帮助!

也查看这些帖子:

Table View Cell custom drawing 1

Table View Cell custom drawing 2

Table View Cell custom drawing 3

答案 1 :(得分: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

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

像魅力一样工作!

答案 2 :(得分:3)

尝试在初始化中设置cell.backgroundColor = [UIColor clearColor]

答案 3 :(得分:1)

虽然我同意接受的答案,但这是我对记录的看法:

如果您不需要任何内置的UITableViewCell功能(滑动,删除,重新排序......),只需将其用作容器来绘制自定义内容,那么您可能需要考虑删除所有单元格tableview中的子视图:willDisplayCell:ForRowAtIndexPath。这将使您的绘图再次可见,并将获得最大的性能(因为您摆脱了您不需要的子视图)。