【发布时间】:2014-04-15 14:51:19
【问题描述】:
我最近开始学习在视图上绘制核心图形,但是每次调用setNeedsDisplay 时,方法都会运行但不会触发drawRect。在我的项目中,我在视图控制器上有一个视图。该视图包含drawRect 中的 if 语句,用于检查 BOOL 变量是 YES 还是 NO。如果是,它使用代码绘制一个红色圆圈。如果否,则绘制一个蓝色圆圈。在 BOOL 的设置器中,它调用 setNeedsDisplay。我在 ViewController 中创建了这个视图类的一个实例并设置了 BOOL 但视图没有重绘。为什么没有调用该方法?我在下面发布了 xcode 文件和代码位。
Customview.m:
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
-(void)awakeFromNib{
[self setup];
}
-(void)setup{
_choice1 = YES;
}
-(void)setChoice1:(BOOL)choice1{
_choice1 = choice1;
[self setNeedsDisplay];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
if (_choice1) {
UIBezierPath * redCircle = [UIBezierPath bezierPathWithOvalInRect:rect];
[[UIColor redColor]setFill];
[redCircle fill];
}else if (!_choice1){
UIBezierPath * blueCircle = [UIBezierPath bezierPathWithOvalInRect:rect];
[[UIColor blueColor]setFill];
[blueCircle fill];
}
}
@end
CustomView.h:
#import <UIKit/UIKit.h>
@interface CustomView : UIView
@property (nonatomic) BOOL choice1;
@end
ViewController.m:
#import "ViewController.h"
#import "CustomView.h"
@interface ViewController ()
- (IBAction)Change:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Change:(id)sender {
CustomView * cv = [[CustomView alloc]init];
[cv setChoice1:NO];
}
@end
完整项目:https://www.mediafire.com/?2c8e5uay00wci0c
谢谢
【问题讨论】:
标签: ios objective-c core-graphics drawrect setneedsdisplay