2014-09-03 39 views
0

我是iOS新手,所以它可能非常简单。什么重要 - 我想使用绘图,而不是添加子视图。我需要用公开的方法来做。试图做到这一点,像这样:在UITableView中绘制文本 - 文字不显示

@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]; 
} 

我想我会错过一些简单的像绘制,但不知道设置背景..此外,有没有任何一个行命令擦掉这个视图中绘制的东西吗?

回答

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; 
} 
0

NSString drawAtPoint:withFont:使用上下文堆栈,并从我调用此方法的位置堆栈是空的。用

UIGraphicsPushContext(context); and UIGraphicsPopContext(); 打了个电话。