drawRect没有从setNeedsDisplay调用

时间:2014-04-15 14:51:20

标签: ios objective-c core-graphics drawrect setneedsdisplay

我最近开始学习核心图形以绘制视图,但每次调用setNeedsDisplay时,该方法都会运行,但不会触发drawRect。在我的项目中,我有一个视图控制器的视图。该视图在drawRect中包含一个if语句,用于检查BOOL变量是YES还是NO。如果是,则使用代码绘制红色圆圈。如果不是,则绘制一个蓝色圆圈。在BOOL的setter中,它调用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

由于

1 个答案:

答案 0 :(得分:1)

您需要在CustomView中为ViewController创建一个插座。删除创建新CustomView实例的代码,并使用_cv引用customView。

@interface ViewController ()
- (IBAction)Change:(id)sender;

@property (weak,nonatomic) IBOutlet CustomView *cv;

@end

然后,在故事板中,将ViewController的cv插座连接到CustomView。此外,您还需要在initFromCoder:上实施CustomView方法。

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self setup];
    }
    return self;
}