2010-06-18 36 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

相關問題