我最近开始学习核心图形以在视图上绘制,但每次调用时setNeedsDisplay
,该方法都会运行但不会触发drawRect
。在我的项目中,我在视图控制器上有一个视图。该视图包含一个 if 语句,drawRect
用于检查 BOOL 变量是 YES 还是 NO。如果是,它使用代码绘制一个红色圆圈。如果否,则绘制一个蓝色圆圈。在 BOOL 的设置器中,它调用setNeedsDisplay
. 我在 ViewController 中创建了这个视图类的一个实例并设置了 BOOL 但视图没有重绘。为什么没有调用该方法?我在下面发布了 xcode 文件和代码位。
自定义视图.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
自定义视图.h:
#import <UIKit/UIKit.h>
@interface CustomView : UIView
@property (nonatomic) BOOL choice1;
@end
视图控制器.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
谢谢