Question

I'm having issues with overriding the UIButton class and customising it.

I have a block class which uses the UIButton class:

#import "Block.h"

@implementation Block

-(id)initWithWidth:(int)width withHeight:(int)height withXPos:(double)x withYPos:(double)y{
    _width=width;
    _height=height;
    _x=x;
    _y=y;
    self = [super initWithFrame:[self createRect]];
    return self;
}

- (CGRect)createRect{
    CGRect background= CGRectMake(_x, _y, _width, _height);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(context, background);
    return background;
}


@end

All i'm trying to do is then add an instance of the Block class to my view:

#import "ViewController.h"
#import "Block.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    Block* b = [[Block alloc]initWithWidth:200 withHeight:200 withXPos:0 withYPos:200];
    [self.view addSubview:b];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Really confused as to why this doesn't work!

Thanks in advance.

Was it helpful?

Solution

Where do you call createRect? That is not a UIView method and will never get called on its own. Did you mean to use drawRect: instead?

Also, is there a reason you made a custom initializer and didn't just override initWithFrame:? You are seemingly accomplishing the same thing in a needlessly complicated way.

EDIT: I see what is happening now. You are calling it when calling the super initializer. Have you tried converting it to drawRect: Instead? As it is now you are attempting to perform drawing before the view is even on the screen.

Here is an example that should work just fine:

#import "Block.h"

@implementation Block

-(id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        // put any extra customization here, although your example doesn't require any
    }
    return self;
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(context, rect);
}

@end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top