无法使用UILabel绘制TextInRect

时间:2011-06-26 07:45:01

标签: iphone objective-c cocoa-touch uilabel quartz-graphics

我想在我的手机上画一个UILabel。出于性能原因,我不想将其添加为子视图。我正在做以下事情:

-(void)drawContent
{
    usernameLabel.text = [message valueForKey:@"user_login"];
    usernameLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
    usernameLabel.textColor = [UIColor blackColor];
    [usernameLabel drawTextInRect:CGRectMake(77, 5, 200, 20)];
}

但是我收到了很多错误:

<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
<Error>: CGContextSetFont: invalid context 0x0
<Error>: CGContextSetTextMatrix: invalid context 0x0
<Error>: CGContextSetFontSize: invalid context 0x0
<Error>: CGContextSetTextPosition: invalid context 0x0
<Error>: CGContextShowGlyphsWithAdvances: invalid context 0x0

4 个答案:

答案 0 :(得分:1)

你应该在UIView的drawRect:实现中调用任何绘图方法。如果我没记错的话,UITableViewCells用于直接支持绘图,您可以在UITableViewCell子类中执行以下操作:

- (void) drawRect: (CGRect) rect
{
    [self drawContent];
}

由于各种原因,现在这是一种沮丧的做法。但是,您仍然可以创建一个自定义UIView子类,该子类绘制实际的单元格内容,将其添加到单元格contentView并让其实现drawRect:,您可以在其中发送drawTextInRect:。这将按预期工作。

答案 1 :(得分:0)

我从未尝试过使用drawTextInect,但您可以尝试这种方式:

 cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, cell.frame.size.width,   cell.frame.size.height)];

cell.selectionStyle = UITableViewCellSelectionStyleNone;
cellLabel.backgroundColor = [UIColor clearColor];
cellLabel.font = [UIFont boldSystemFontOfSize:14];
cellLabel.lineBreakMode = UILineBreakModeWordWrap;
[cell.contentView addSubview:cellLabel];

希望这有帮助!!

答案 2 :(得分:0)

要绘制UILabel,只需在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中创建并添加UILabel到单元格contentView。

无需直接致电drawTextInRect:。这只应用于子类化UILabel单元格并使用替代实现覆盖该方法。直接在代码中调用方法会导致这些错误,因为系统尚未设置要绘制的图形上下文。

编辑使用示例参考进行更新:

如果您想自己绘制表格的单元格,请查看Apple提供的TableViewSuite。在那里你将找到5_CustomTableViewCell / Classes / TimeZoneView,它被用作5_CustomTableViewCell / Classes / TimeZoneCell的内容子视图。 TimeZoneView显示如何在不使用UILabel的情况下直接将自定义文本绘制到视图中。

答案 3 :(得分:0)

您是否阅读了方法documentation

此方法仅用于子类化,并且您收到错误,因为没有定义绘图上下文,这与UILabel实例相关,而不是在调用drawContent的地方。如果您希望在不同的视图中绘制文本,请使用NSString实例。它提供了drawing extensions