Search code examples
swiftif-statementbordersubtraction

create a if statement where only one button at a time can have a border


I want my swift code to use a if statement or another sequence to only display a border on one of the buttons if click at a time. So a border can only be seen on one button at a time that button would be the last one pressed. I know I could say layer.border with 0 on each button that should be selected but I want to see if there is a more efficient way to do this.

import UIKit

class ViewController: UIViewController {
    
    var ba = UIButton()
    var bb = UIButton()
    var bc = UIButton()
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        [ba,bb,bc].forEach {
            
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
        }
        ba.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        bb.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
        bc.frame = CGRect(x: 200, y: 0, width: 100, height: 100)
        
        ba.backgroundColor = .blue
        bb.backgroundColor = .orange
        bc.backgroundColor = .darkGray
        ba.addTarget(self, action: #selector(pressa), for: .touchDown)
        bb.addTarget(self, action: #selector(pressb), for: .touchDown)
        bc.addTarget(self, action: #selector(pressc), for: .touchDown)
        
        
    }
    
    @objc func pressa(){
        ba.layer.borderWidth = 2
        
    }
    @objc func pressb(){
        bb.layer.borderWidth = 2
      }
    @objc func pressc(){
          bc.layer.borderWidth = 2
      }


}

Solution

  • you can add target to all buttons at the forEach and be only one method as @Sh_Khan mention

    import UIKit
    
    class ViewController: UIViewController {
        
        var ba = UIButton()
        var bb = UIButton()
        var bc = UIButton()
        
        
    
        override func viewDidLoad() {
            super.viewDidLoad()
            [ba,bb,bc].forEach {
                
                $0.translatesAutoresizingMaskIntoConstraints = false
                view.addSubview($0)
          $0.addTarget(self, action: #selector(pressAll(_:)), for: .touchDown)
            }
            ba.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
            bb.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
            bc.frame = CGRect(x: 200, y: 0, width: 100, height: 100)
            
            ba.backgroundColor = .blue
            bb.backgroundColor = .orange
            bc.backgroundColor = .darkGray 
        }
        
      @objc func pressAll(_ sender:UIButton) {
        [ba,bb,bc].forEach { $0.layer.borderWidth = 0 } // reset all
        sender.layer.borderWidth = 2 
    }
       
    
    }