2014-09-04 84 views
1

嘿,我有一個類RqButton派生自UIButton,我用它來個性化我的按鈕。用initWithFrame傳遞另一個參數:CGRectMake()

如果如果做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];不會像這樣工作,但現在,真正做到這一點的方式是什麼?

感謝您的幫助,亞歷克斯

回答

5

所有你需要做的是建立內RqButton新init方法將使用initWithFramesuper。將另一個參數添加到自定義初始化中使用的自定義init中。

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

確保此方法添加到您的頭文件,以及讓你可以公開訪問。現在您還可以從任何你想要的這個方法來init您RqButton像這樣:

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

乾杯伴侶,完美的解決方案! – user2875404 2014-09-04 16:57:53

相關問題