单击button1时如何更改swift中button2的颜色? [英] How to change Color of button2 in swift when button1 is clicked?

查看:131
本文介绍了单击button1时如何更改swift中button2的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是在点击fiveMinButton时更改fiveMinButton和tenMinButton的 backgroundColor 。为什么这段代码不起作用? @IBAction 也不起作用。

All I want to do is change the backgroundColor of fiveMinButton and tenMinButton when fiveMinButton is clicked. Why doesn't this code work? @IBAction will not work either.

@IBOutlet weak var fiveMinButton: UIButton!



 override func viewDidLoad() {
    super.viewDidLoad()

    fiveMinButton.addTarget(self, action: Selector(("action:")), for: UIControlEvents.touchUpInside)

    func action(sender: UIButton){

        if sender === fiveMinButton {

            fiveMinButton.backgroundColor = UIColor.gray
            tenMinButton.backgroundColor = UIColor.lightgray

        }

    }


推荐答案

您的代码存在2个问题。

There is 2 problems with your code.


  1. 选择器的语法错误

  2. 您已在<$ c $中添加了按钮的操作c> viewDidLoad 这也是错误的,所以将该方法写在 viewDidLoad 之外作为类方法。

  1. The syntax of selectoris wrong
  2. You have added action of your button inside the viewDidLoad that will also wrong, so write that method outside the viewDidLoad as class method.

对于这样的第一个更改选择器。

For first one change selector like this.

fiveMinButton.addTarget(self, action: #selector(action(sender:)), for: UIControlEvents.touchUpInside)

对于第二个问题,只需在 viewDidLoad 旁边写下操作。

For second problem just write action out side the viewDidLoad.

这篇关于单击button1时如何更改swift中button2的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆