0

我知道如何设置 enable = YES/NO,一个使用属性和 xib 创建的按钮。但是,您如何从同一类中的另一个方法对以编程方式创建的按钮执行相同的操作?

例如,这是我在 viewDidLoad 中的按钮:

UIButton *AllList = [UIButton buttonWithType:UIButtonTypeCustom];
AllList.frame = CGRectMake(40, 80, 107.f, 53.5f); //set frame for button

UIImage *buttonImageFull = [UIImage imageNamed:@"allModsBtn.png"];
[AllList setBackgroundImage:buttonImageFull forState:UIControlStateNormal];
[self.view addSubview:AllList];

// add targets and actions
[AllList addTarget:self action:@selector(getButtons:) forControlEvents:UIControlEventTouchUpInside];    
AllList.tag = 0;

我想用另一种方法将此按钮的启用设置为“是”或“否”。

4

4 回答 4

1
@implementation {
     UIButton *myButton;
}

- (void)viewDidLoad {
    myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myButton.tag = 121;
    myButton.frame = CGRectMake(40, 80, 107.f, 53.5f); //set frame for button

    UIImage *buttonImageFull = [UIImage imageNamed:@"allModsBtn.png"];
    [myButton setBackgroundImage:buttonImageFull forState:UIControlStateNormal];
    [self.view addSubview:myButton];

   // add targets and actions
   [myButton addTarget:self action:@selector(getButtons:)       
   forControlEvents:UIControlEventTouchUpInside];    
   myButton.tag = 0;
}

- (void)someOtherMethod {

   myButton.enabled = YES;

OR

  //In this case you dont need to define uibutton to globaly

   UIButton *button = (UIButton*)[[self view] viewWithTag:121];
   [button setEnabled:YES];

}
于 2012-10-17T18:57:05.120 回答
0

像这样的东西:

UIButton *myButton = [self.view viewWithTag:BUTTON_TAG]; // in your case is 0
[myButton setEnabled:YES];
于 2012-10-17T15:55:10.790 回答
0

有两种方法:

1)你可以把它变成一个ivar,然后

AllList.enabled = YES;

或者

[AllList setEnabled:YES];

2)为按钮设置一个唯一的标签

UIButton *AllList = [UIButton buttonWithType:UIButtonTypeCustom];
AllList.frame = CGRectMake(40, 80, 107.f, 53.5f); //set frame for button
AllList.tag = kUNIQUE_TAG;

在你想弄乱按钮的启用属性的方法中

UIButton *theButton = (UIButton *)[self viewWithTag:kUNIQUE_TAG];
[theButton setEnabled:YES];
于 2012-10-17T16:02:06.737 回答
0

您必须使该按钮成为视图控制器的 ivar。

@implementation {
    UIButton *myButton;
}

- (void)viewDidLoad {
    myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myButton.frame = CGRectMake(40, 80, 107.f, 53.5f); //set frame for button

    UIImage *buttonImageFull = [UIImage imageNamed:@"allModsBtn.png"];
    [myButton setBackgroundImage:buttonImageFull forState:UIControlStateNormal];
    [self.view addSubview:myButton];

    // add targets and actions
    [myButton addTarget:self action:@selector(getButtons:)       
       forControlEvents:UIControlEventTouchUpInside];    
    myButton.tag = 0;
}

- (void)someOtherMethod {
    myButton.enabled = YES;
}
于 2012-10-17T15:54:55.050 回答