简体   繁体   中英

Pass another argument with initWithFrame:CGRectMake()

Hey I have a class RqButton deriving from UIButton that I use to personalise my buttons.

If If do button = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, sq, sq)]; everything is working as expected but I want to pass another parameter to RqButton and I don't know how.

This is my RqButton.m

#import "RqButton.h"

@implementation RqButton


+ (RqButton *)buttonWithType:(UIButtonType)type
{return [super buttonWithType:UIButtonTypeCustom];}

- (void)drawRect:(CGRect)rect r:(int)r
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    float width =  CGRectGetWidth(rect);
    float height =  CGRectGetHeight(rect);

    UIColor *borderColor = [UIColor colorWithRed:0.99f green:0.95f blue:0.99f alpha:1.00f];


    CGFloat BGLocations[2] = { 0.0, 1.0 };
    CGFloat BgComponents[8] = { 0.99, 0.99, 0.0 , 1.0,
        0.00, 0.00, 0.00, 1.0 };
    CGColorSpaceRef BgRGBColorspace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef bgRadialGradient = CGGradientCreateWithColorComponents(BgRGBColorspace, BgComponents, BGLocations, 2);

    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, width, height) cornerRadius: 5];
    [roundedRectanglePath addClip];

    CGPoint startBg = CGPointMake (width*0.5, height*0.5);
    CGFloat endRadius= r;

    CGContextDrawRadialGradient(ctx, bgRadialGradient, startBg, 0, startBg, endRadius, kCGGradientDrawsAfterEndLocation);
    CGColorSpaceRelease(BgRGBColorspace);
    CGGradientRelease(bgRadialGradient);

    [borderColor setStroke];
    roundedRectanglePath.lineWidth = 2;
    [roundedRectanglePath stroke];
}

@end

You see that I want to be able to call the class while passing the CGrect and the int r in order to use it in the line CGFloat endRadius= r;

Of course, button = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, sq, sq) :1]; wouldn't work like this, but now, what's the way of actually doing it?

Thanks for your help, Alex

All you need to do is create a new init method within RqButton that will use the initWithFrame 's super . Add another parameter to your custom init to use within the custom initialization.

RqButton.m

- (id)initWithFrame:(CGRect)rect radius:(CGFloat)r
{
    if(self = [super initWithFrame:rect])
    {
        // apply your radius value 'r' to your custom button as needed.
    }
    return self;
}

Make sure to add this method to your header file as well so that you can access it publicly. You can now call this method from wherever you want to init your RqButton like so:

RqButton *customButton = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, sq, sq) radius:2.0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM