2010-06-18 71 views
0

我已经创建了一个名为Status的UIView的子类,它被设计为根据变量的值显示一定大小的矩形(在视图内)。我可以使用drawRect刷新UIView子类吗?

// Interface 
#import <Foundation/Foundation.h> 
#import <QuartzCore/QuartzCore.h> 

@interface Status: UIView { 
    NSString* name; 
    int someVariable; 
    } 

@property int someVariable; 
@property (assign) NSString *name; 

- (void) createStatus: (NSString*)withName; 
- (void) drawRect:(CGRect)rect; 

@end 

// Implementation 
#import "Status.h" 
@implementation Status 
@synthesize name, someVariable; 

- (void) createStatus: (NSString*)withName { 
    name = withName; 
    someVariable = 10000; 
} 

- (void) drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    //Draw Status 
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1); // fill  
    CGContextFillRect(context, CGRectMake(0.0, 0.0, someVariable, 40.0)); 
} 

//// myviewcontroller implementation 
    - (void) viewDidAppear:(BOOL)animated { 
     [super viewDidAppear:animated]; 
     myStatus = [[Status alloc] initWithFrame:CGRectMake(8,8,200,56)]; 
     myStatus.backgroundColor = [UIColor grayColor]; 
     [self.view addSubview:myStatus]; 
    } 

我该如何设置,以便我可以反复调用状态栏的刷新?我可能会使用NSTimer每秒钟刷新4次,我只是不确定要调用什么,或者如果我应该将这个矩形绘图移动到单独的函数或其他东西...

在此先感谢帮助:)

回答

1

只需使用

[self.view setNeedsDisplay]; 

从您的视图控制器。您可能希望在主线程中实现此目的,因此可能将其包含在内performSelectorOnMainThread:withObject:waitUntilDone:

如果您还需要指定,也可以使用setNeedsDisplayInRect:。但是你的代码是轻量级和快速的,你可能需要计算更新区域来计算包含rect。所以我只是更新整个UIView,如果它不显着减慢你的应用程序。作为一个方面说明,你可能想让你的名字属性(副本),所以它不会改变你的脚下(并在createSatus中使用self.name = ...来使用属性访问器。在这种情况下,请不要忘记释放它的dealloc中

而不是调用setNeedsDisplay的:从您的视图控制器,我建议从自身观点属性发生变化时内调用此

+0

太容易了,这是完美的:)。 – Timbo 2010-06-19 23:51:42

相关问题