Reputation: 404
Hi I am new to iOS programming. I am writing a iOS application and implemented few UIButtons. I have to set the properties for these buttons. So instead of writing repetitive code for each button, I implemented separate method to basically set the properties. Code is given below
-(void)abc{
_xCord = self.view.bounds.size.width/2.0f;
_yCord = self.view.bounds.size.height/2.0f;
[self setButtonProperties:_def]; // def is ivar UIButton
_xCord+=50;
_yCord+=50;
[self setButtonProperties:_ghi]; // ghi is ivar UIButton}
Set button properties is given below
- (void)setButtonProperties:(UIButton *)button{
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(_xCord, _yCord, 50, 50);
button.clipsToBounds = YES;
button.layer.cornerRadius = 50/2.0f;
button.layer.borderColor = [UIColor redColor].CGColor;
button.layer.borderWidth = 2.0f;
[self.view addSubview:button];
}
Here the button is added to view but it is not reflected with iVar UIButton.When I implement the target methods for button actions the respective methods of buttons are not called. Is there a way to send UIButton as reference or any other way I can achieve the same so that setButtonProperties method actually set ivar UIButton properties.
Thanks in advance
Upvotes: 0
Views: 97
Reputation: 2778
To keep the same reference of the new button object which you create on this method, you need to have your method like this:
- (void)setButtonProperties:(UIButton **)button{
UIButton *tempBbutton = [UIButton buttonWithType:UIButtonTypeCustom];
tempBbutton.frame = CGRectMake(_xCord, _yCord, 50, 50);
tempBbutton.clipsToBounds = YES;
tempBbutton.layer.cornerRadius = 50/2.0f;
tempBbutton.layer.borderColor = [UIColor redColor].CGColor;
tempBbutton.layer.borderWidth = 2.0f;
[self.view addSubview:tempBbutton];
*button = tempButton;
}
This is how the error object is created and saves on the same memory of the error object (&error) which we pass on method.
Upvotes: 0
Reputation: 1496
You can pass the ivar by reference like this (adding & to the ivars and adjusting the setButtonProperties method). But since your code really don't need this I suggest your code returns the button like Pravin Tate suggests.
-(void)abc{
_xCord = self.view.bounds.size.width/2.0f;
_yCord = self.view.bounds.size.height/2.0f;
[self setButtonProperties:&_def]; // def is ivar UIButton
_xCord+=50;
_yCord+=50;
[self setButtonProperties:&_ghi]; // ghi is ivar UIButton}
NSLog(@"foo");
}
- (void)setButtonProperties:(UIButton * __strong *)button{
*button = [UIButton buttonWithType:UIButtonTypeCustom];
(*button).frame = CGRectMake(_xCord, _yCord, 50, 50);
(*button).clipsToBounds = YES;
(*button).layer.cornerRadius = 50/2.0f;
(*button).layer.borderColor = [UIColor redColor].CGColor;
(*button).layer.borderWidth = 2.0f;
[self.view addSubview:*button];
}
Upvotes: 2