Newbee
Newbee

Reputation: 3301

How to pass UIButton to a function and create there...?

Question may look so stupid, just got problem in some basics of objective C. I'm aware objective C only support pass by value however my requirement needs to pass address. I have a UIButton member variable (iVar) and I'm passing these to a function and trying to alloc init inside the function using parameters like below...

Function Call:

[self create_button : ivar_btn];

Definition:

- (void) create_button : (UIButton*) button
{
    // Create button
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"00/00/0000" forState:UIControlStateNormal];
    [self.add_scroll_view addSubview:button];
}

So without pass by reference in objective C, how do I handle this case?

Please correct me if I understood anything wrong.

NOTE: Create button is a common code, I have been using this to create buttons at run time depend on req.

Thanx

Upvotes: 0

Views: 181

Answers (3)

Shahab Qureshi
Shahab Qureshi

Reputation: 952

I tried your code, it is working fine for me. just you missing one thing. Setting its frame.

Here is how I amend your code and works fine for me. Hope it will work for you as well.

UIButton *btn = [[UIButton alloc] init];
[self create_button:btn];

and Function/Method:

- (void) create_button : (UIButton*) button
{
    // Create button
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"00/00/0000" forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0, 0, 100,100)];
    [self.view addSubview:button];
}

works fine

Upvotes: 0

Vishal Singh
Vishal Singh

Reputation: 4480

This is useless implementation and I have not tried it but still.

UIButton *ivar_btn = nil;   
    [self create_button : &ivar_btn];
- (void) create_button : (UIButton**) button
    {
        // Create button
        *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [*button setTitle:@"00/00/0000" forState:UIControlStateNormal];
        [self.add_scroll_view addSubview:*button];
    }

Upvotes: 2

Bhavin_m
Bhavin_m

Reputation: 2784

Try this....

- (void) create_button : (UIButton*) button
{
    // Create button
    UIButton *tmpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    tmpButton = button;
    [self.add_scroll_view addSubview:tmpButton];
}

Upvotes: 0

Related Questions