Question

I have recently started learning core graphics to draw on views, but every time I call setNeedsDisplay, the method runs but doesn't trigger drawRect. In my project, I have a view on a view controller. The view contains an if statement in drawRect that checks if a BOOL variable is YES or NO. If YES, it uses the code to draw a red circle. If NO, it draws a blue circle. In the BOOL's setter, it calls setNeedsDisplay. I create an instance of this view class in the ViewController and set the BOOL but the view is not redrawing. Why is the method not getting called? I posted the xcode files and code bits below.

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

Full project: https://www.mediafire.com/?2c8e5uay00wci0c

Thanks

Was it helpful?

Solution

You need to create an outlet for your CustomView in your ViewController. Delete the code that creates the new CustomView instance and use _cv to refer to the customView.

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

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

@end

Then, in the storyboard, connect ViewController's cv outlet to the CustomView. Also, you'll need to implement the initFromCoder: method on CustomView.

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self setup];
    }
    return self;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top