首页 > 解决方案 > 如何将@IBAction Func 引用到几个按钮插座

问题描述

我有很多按钮,按下时会运行非常相似的代码,我目前正在为每个按钮编写一个函数,有没有办法将其压缩为一个函数?

继承人的一些代码:

   @IBAction func b0(_ sender: UIButton) {
        if  pressedArray[0] && buttonsCanBePressed {
            pressedArray[0] = false
            b0.backgroundColor = notPressedColour
        } else if buttonsCanBePressed {
            b0.backgroundColor = pressedColour
            pressedArray[0] = true
        }
    }



    @IBAction func b1(_ sender: UIButton) {
        if  pressedArray[1] && buttonsCanBePressed {
            pressedArray[1] = false
            b1.backgroundColor = notPressedColour
        } else if buttonsCanBePressed {
            b1.backgroundColor = pressedColour
            pressedArray[1] = true
        }
    }

    @IBAction func b2(_ sender: UIButton) {
        if  pressedArray[2] && buttonsCanBePressed {
            pressedArray[2] = false
            b2.backgroundColor = notPressedColour
        } else if buttonsCanBePressed {
            b2.backgroundColor = pressedColour
            pressedArray[2] = true
        }
    }

标签: swiftxcodeuibutton

解决方案


是的,你可以只做一个IBAction函数,然后将行号中的圆圈拖到你想要的所有按钮上,你可以使用sender.tag来区分按钮

在此处输入图像描述


推荐阅读