Can I use drawRect to refresh a UIView subclass?
I've created a subclass of UIView called Status which is designed to display a rectangle of a certain size (within a view) depending on the value of a variable.
// 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 S开发者_如何转开发tatus
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];
}
How do I set this up so I can repeatedly call a refresh of the status bar? I'll probably call the refresh 4 times per second using a NSTimer, I'm just not sure what to call or if I should move this rectangle drawing to a separate function or something...
Thanks in advance for your help :)
Just use
[self.view setNeedsDisplay];
from your view controller. You probably want to make this happen on the main thread, so maybe wrap it up with performSelectorOnMainThread:withObject:waitUntilDone:
There is setNeedsDisplayInRect:
if you need to specify that, too. But your code is lightweight and fast, and you probably need to make calculations for the updated region to calculate the containing rect. So I'd just update the whole UIView if it doesn't appear to slow down your application significantly.
As a side note, you probably want to make your name property (copy), so it doesn't change under your feet (and use self.name = ...
in createSatus to use the property accessors. In that case, don't forget to release it in dealloc.
Instead of calling setNeedsDisplay: from your view controller, I'd suggest to call this from within the view itself whenever the property changes.
精彩评论