Search code examples
swiftibaction

Best way to control multiple multiple buttons


I'm new to swift so please pardon me if this is a stupid question. I have a list of button in my program. When any button is clicked, the same action will be applied to that specific button (change the background picture).

Initially I created an individual button and individual IBaction for each of the button. I figured that is too stupid. After I searched here I learned that I can create an array for the button and link them to the same action. Hence the following code.

@IBAction func unselectPai(sender: UIButton) {
    switch sender{
        case pai[0]:
        unselectPaiHelper(0)
        case pai[1]:
        unselectPaiHelper(1)
        case pai[2]:
        unselectPaiHelper(2)
        case pai[3]:
        unselectPaiHelper(3)
        case pai[4]:
        unselectPaiHelper(4)
        case pai[5]:
        unselectPaiHelper(5)
        case pai[6]:
        unselectPaiHelper(6)
        case pai[7]:
        unselectPaiHelper(7)
        case pai[8]:
        unselectPaiHelper(8)
        case pai[9]:
        unselectPaiHelper(9)
        case pai[10]:
        unselectPaiHelper(10)
        case pai[11]:
        unselectPaiHelper(11)
        case pai[12]:
        unselectPaiHelper(12)
        case pai[13]:
        unselectPaiHelper(13)
        default: return
    }
}

However, I feel there gotta be even easier way to do this and would appreciate some pointer.


Solution

  • Like this:

    @IBAction func unselectPai(sender: UIButton) {
        if let ix = pai.indexOf(sender) {
            unselectPaiHelper(ix)
        }
    }