Search code examples
iosswift3uibuttontouchesbegan

Make multiple buttons highlight when touch begins


enter image description here

I have placed three buttons together in a view each of which will have a different profile image. I need all three buttons to highlight when touch begins on any individual one so that the three together appear to be one button. I have tried the following code but it does not work. Any ideas?

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap))
    tapGesture.numberOfTapsRequired = 1
    friendsBtn1.addGestureRecognizer(tapGesture)

    func normalTap(sender: UITapGestureRecognizer){
        if sender.state == .began {
            friendsBtn2.isHighlighted = true
            friendsBtn3.isHighlighted = true
        }
        if sender.state == .ended {
            friendsBtn2.isHighlighted = false
            friendsBtn3.isHighlighted = false
        }
        print("Normal tap")
    }

Solution

  • I did solve the problem. Here is the code.

    [friendsBtn1, friendsBtn2, friendsBtn3].forEach { button in
            button?.addTarget(self, action:#selector(highlightAllButtons(sender:)), for: .touchDown)
            button?.addTarget(self, action:#selector(unhighlightAllButtons(sender:)), for: [.touchUpInside, .touchUpOutside])
        }
    
    func highlightAllButtons(sender: UIButton) {
        [friendsBtn1, friendsBtn2, friendsBtn3].forEach { button in
            button.isHighlighted = true
        }
    }
    func unhighlightAllButtons(sender: UIButton) {
        [friendsBtn1, friendsBtn2, friendsBtn3].forEach { button in
            button.isHighlighted = false
        }
    }