通过引用传递UIButton

时间:2015-07-21 06:36:32

标签: ios iphone uibutton

您好我是iOS编程新手。我正在编写iOS应用程序并实现了一些UIButtons。我必须设置这些按钮的属性。因此,我没有为每个按钮编写重复的代码,而是实现了基本设置属性的单独方法。 代码如下:

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

设置按钮属性如下所示

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

此处按钮被添加到视图中但不会反映在iVar UIButton中。当我实现按钮动作的目标方法时,不会调用各个按钮方法。有没有办法发送UIButton作为参考或任何其他方式我可以实现相同,以便setButtonProperties方法实际设置ivar UIButton属性。

提前致谢

2 个答案:

答案 0 :(得分:2)

您可以像这样通过引用传递ivar(向ivars添加&并调整setButtonProperties方法)。但由于您的代码确实不需要这个,我建议您的代码返回像Pravin Tate建议的按钮。

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

答案 1 :(得分:0)

要保留您在此方法上创建的新按钮对象的相同引用,您需要使用以下方法:

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

这是错误对象的创建方式,并保存在我们传递方法的错误对象(& error)的同一内存中。