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

如果执行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

最佳答案

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

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;
}

确保也将此方法添加到头文件中,以便可以公开访问它。现在,您可以从任何要调用RqButton的位置调用此方法,如下所示:
RqButton *customButton = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, sq, sq) radius:2.0];

关于ios - 通过initWithFrame:CGRectMake()传递另一个参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25668921/

10-11 20:04