触摸时改变按钮的颜色

时间:2015-10-30 12:50:50

标签: ios objective-c uibutton

我试图在按下按钮时更改按钮的颜色和图像。这就是我所拥有的

 - (IBAction)likeButtonTouched:(UIButton*)sender {
sender.imageView.image = [sender.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[sender setImage: [UIImage imageNamed:@"Like Filled"] forState:UIControlStateNormal];
[sender setTintColor:secondaryColor];
}

此代码适用于viewDidLoad,但在此中,色调颜色未更改,但图像为。谁知道为什么?

4 个答案:

答案 0 :(得分:1)

您可以使用以下方法覆盖UIButton的方法。 只需在按钮处于突出显示状态时更改按钮的背景颜色。

- (void)setHighlighted:(BOOL)highlighted {
      [super setHighlighted:highlighted];

      if (highlighted) {
          self.backgroundColor = [UIColor redColor]; // whatever color you want
     }
}

答案 1 :(得分:0)

我编写了一个UIButton的子类,它在不久前做了类似的事情:

@implementation OnTouchHighlightButton

- (void)awakeFromNib
{
    [super awakeFromNib];

    [self addActionSelectors];
}

- (void)addActionSelectors
{
    [self addTarget:self action:@selector(onTouchDown) forControlEvents:(UIControlEventTouchDown | UIControlEventTouchDragEnter)];
    [self addTarget:self action:@selector(onTouchUp) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit | UIControlEventTouchCancel)];
}

- (void)onTouchDown
{
    [UIView transitionWithView:self
                      duration:0.15
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        self.highlighted = YES;
                    }
                    completion:nil];
}

- (void)onTouchUp
{
    [UIView transitionWithView:self
                      duration:0.15
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        self.highlighted = NO;
                    }
                    completion:nil];
}

@end

您可以在onTouchUp和onTouchDown方法上添加任何内容。您还可以更改触发这些方法的控制事件。

答案 2 :(得分:0)

不幸的是,Apple没有为UIButton上的tintColor和backgroundColor属性提供// CHECKING ANSWER WITH AJAX CALL var answer = $('input[name=answer]:checked').val(), currentQuestionId = $('.question').attr('id'), token = '{{ csrf_token() }}'; $.ajax({ type: "POST", url: '/quiz/' + {{$quiz[0]->id}} +'/check', data: { 'currentQuestionId': currentQuestionId, 'answer': answer, '_token': token }, success: function (data) { } }); setter方法,因此您必须使用控件事件。但是,您不必为UIButton创建子类。

forState:

答案 3 :(得分:-3)

很抱歉上次回复;有些人得错了。

这里我在Swift 3.0中更新答案;希望它可以根据您的查询运行良好;

@IBOutlet weak var colorChangeBtn: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()
    colorChangeBtn.backgroundColor = UIColor.blue
    colorChangeBtn.tintColor = UIColor.cyan
    colorChangeBtn.setImage(#imageLiteral(resourceName: "select.png"), for: UIControlState.normal)
  }

@IBAction func colorChange(_ sender: UIButton) {
    sender.backgroundColor = UIColor.red
    sender.tintColor = UIColor.blue
    sender.setImage(#imageLiteral(resourceName: "focus.png"), for: .normal)
  }