Custom Bonbons
Custom Bonbons

Reputation: 1699

Sending extra parameters in UIButton instance

Is it possible to send extra parameters when I instantiate this button class, like so:?

BttClass *myButton = [[BttClass alloc] init];

If so, what is the correct syntax? I have been trying all sorts! I would like to send a BOOL and a string. Thanks.

Upvotes: 0

Views: 171

Answers (3)

Damo
Damo

Reputation: 12890

Extend UIButton by subclassing it.

//MyButton.h
@interface MyButton : UIButton {

}

@property (nonatomic, strong) NSString* aString;
@property (nonatomic, weak) BOOL aBool;

You need to define an initialiser method

-(id)initWithStringValue:(NSString *)stringValue andWithBoolValue:(bool)boolValue;

Then implement the initialiser method

//MyButton.m
-(id)initWithStringValue:(NSString *)stringValue andWithBoolValue:(bool)boolValue {
    self = [super init];
    if (self) {
        self.aString = stringValue;
        self.aBool = boolValue;
    }
    return self;
}

In a calling class your code would look like

MyButton* myButton = [[MyButton alloc] initWithStringValue:@"tralala" andWithBoolValue:YES];

Upvotes: 2

Aatish Molasi
Aatish Molasi

Reputation: 2186

Create your custom button

in your

CustomButton.h

@interface CustomButton : UIButton

    - (id)initWithBooleanValue:(BOOL)value;

@end

and in your CustomButton.m

- (id)initWithBooleanValue:(BOOL)value
{
    self = [super init];
    if (self)
    {
        NSLog(@"Bool = %d",value);
    }
    return self;
}

You can use this class in place of your normal UIButton

Upvotes: 0

melsam
melsam

Reputation: 4977

Just define a custom initializer and pass in your values:

- (id)initWithBoolValue:(bool)boolValue stringValue:(NSString *)stringValue  {
    self = [super init];
    if (self) {
        // Custom initialization
    }
    return self;
}

Upvotes: 0

Related Questions