0

我正在开发一个带有两个 UIButtons 的应用程序,当它们被按下时它们必须改变大小和颜色。我的代码是:

    UIButton *Answer1Button = [UIButton buttonWithType:UIButtonTypeCustom];

    UIButton *Answer2Button = [UIButton buttonWithType:UIButtonTypeCustom];

    [Answer1Button addTarget:self action:@selector(Answer1Action) forControlEvents:UIControlEventTouchUpInside];


    [Answer2Button addTarget:self action:@selector(Answer2Action) forControlEvents:UIControlEventTouchUpInside];

    [Answer1Button setBackgroundColor:[UIColor redColor]];
    [Answer2Button setBackgroundColor:[UIColor yellowColor]];
    Answer1Button.frame = CGRectMake(0, 0, 320, 45);
    Answer2Button.frame = CGRectMake(0, 50, 320, 45);

我为它创建的功能:

-(void)Answer1Action{


[UIButton beginAnimations:nil context:nil];
[UIButton setAnimationDuration:0.5];
self.backgroundColor = [UIColor greenColor];

self.alpha = 0.5;

[UIButton commitAnimations];    
}

我现在遇到的问题是,当我按下 UIButton 时会调用该函数,但 self.alpha 会影响按钮所在的整个 UIView。

我仍然是 Objective-C 的新手,所以我想这可能是我忘记的简单事情。

4

3 回答 3

3
[Answer1Button setBackgroundColor:[UIColor greenColor]];
[Answer1Button setAlpha:0.5];

//Include QuartzCore framework and import it to your viewController.h,and write the below line along with the above code to change the size and to do many animations.

Answer1Button.layer.affineTransform=CGAffineTransformScale(Answer1Button.transform, 1.2, 1.2);
于 2013-11-13T09:34:25.663 回答
1

您正在设置self.alpha = 0.5;,这里 self 不是您的按钮。你应该设置你的按钮:

Answer1Button.backgroundColor = [UIColor greenColor];

Answer1Button.alpha = 0.5;

但这不是最佳做法。您可以将按钮作为参数发送到处理程序方法:(变量和方法名称在 ObjC 中不应以大写字母开头。)

[answer1Button addTarget:self action:@selector(answer1Action:) forControlEvents:UIControlEventTouchUpInside];

并在您的处理程序方法中使用发送者按钮作为参数:

-(void)answer1Action:(id)sender{
UIButton* myButton = (UIButton*)sender;

[UIButton beginAnimations:nil context:nil];
[UIButton setAnimationDuration:0.5];
myButton.backgroundColor = [UIColor greenColor];

myButton.alpha = 0.5;

[UIButton commitAnimations];    
}
于 2013-11-13T09:16:05.233 回答
0

设置按钮 alpha 而不是 self.alpha=0.5;

-(void)Answer1Action{


   [UIButton beginAnimations:nil context:nil];
    [UIButton setAnimationDuration:0.5];
   self.backgroundColor = [UIColor greenColor];

   Answer1Button.alpha = 0.5;

  [UIButton commitAnimations];    
    }
于 2013-11-13T09:19:18.043 回答