在UITableView中绘制文本 - 文本不显示

时间:2014-09-03 20:52:46

标签: ios objective-c uitableview

我是iOS的新手,所以它可能非常简单。重要的是 - 我想使用绘图,而不是添加子视图。我需要在公共方法上做到这一点。试着这样做:

@implementation TripTableViewCell2

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)updateWithTrip:(Trip*)trip
{
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:10.0f],
                                 NSForegroundColorAttributeName: UIColorFromRGB(0x28cdfb)};
    CGSize textSize = [trip.tripId sizeWithAttributes:attributes];
    CGPoint textPoint = CGPointMake(10.0f, 10.0f);
    [trip.tripId drawAtPoint:textPoint withAttributes:attributes];
}

我假设我想念一些简单的东西,例如设置绘图的上下文但不确定..另外,是否有任何单行命令来擦除此视图中绘制的任何内容?

2 个答案:

答案 0 :(得分:1)

问题是当你调用drawAtPoint时,它会绘制到当前上下文中,而不是单元格的上下文。

您需要做的是创建UIView的子类并在drawRect方法中进行绘制。在这里,我创建了这样一个类,并测试它是否按预期工作:

#import "CustomDraw.h"

@implementation CustomDraw

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    NSString *trip = @"My trip";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:20.0f],
                                 NSForegroundColorAttributeName: [UIColor redColor]};
    CGSize textSize = [trip sizeWithAttributes:attributes];
    CGPoint textPoint = CGPointMake(10.0f, 10.0f);
    [trip drawAtPoint:textPoint withAttributes:attributes];
}


@end

enter image description here

在表格单元格中显示视图的一种方法是将其设置为背景视图:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TripCell"];
        cell.backgroundView = [[CustomDraw alloc] init]; // Pass your trip in here

    return cell;
}

答案 1 :(得分:0)

NSString drawAtPoint:withFont:使用了上下文堆栈,从我调用此方法的地方来看,堆栈是空的。用

包裹电话

UIGraphicsPushContext(context); and UIGraphicsPopContext(); 做了伎俩。