使用initWithFrame传递另一个参数:CGRectMake()

时间:2014-09-04 15:05:26

标签: ios objective-c button

嘿,我有一个来自RqButton的课程UIButton,我用它来个性化我的按钮。

如果If button = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, sq, sq)];一切都按预期工作,但我想将另一个参数传递给RqButton而我不知道如何。

这是我的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

你知道我希望能够在传递CGrect和int r时调用该类,以便在行中使用它 CGFloat endRadius = r;

当然,button = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, sq, sq) :1];不会像这样工作,但现在,实际做的是什么?

感谢您的帮助,Alex

1 个答案:

答案 0 :(得分:5)

您需要做的就是在RqButton中创建一个新的init方法,该方法将使用initWithFrame的{​​{1}}。将另一个参数添加到自定义初始化以在自定义初始化中使用。

<强> RqButton.m

super

确保将此方法添加到您的头文件中,以便您可以公开访问它。您现在可以从任何地方调用此方法- (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; } 您的RqButton如下:

init