Array of UIButtons in Swift 4

后端 未结 2 549
名媛妹妹
名媛妹妹 2021-01-14 04:52

I\'ve made a series of checkboxes in UiKit with UIButtons:

@IBOutlet weak var Box1: UIButton!
@IBOutlet weak var Box2: UIButton!
@IBOutlet weak var Box3: UIB         


        
2条回答
  •  一生所求
    2021-01-14 05:32

    It is possible to declare an IBOutlet as array

    • Create an IBOutlet as array

      @IBOutlet var boxes : [UIButton]!
      
    • Connect all buttons to the same outlet (in the desired order)

    • In viewDidAppear use a loop or forEach

      override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
      
          boxes.forEach {
              $0.setImage(BoxOFF, for: .normal)
              $0.setImage(BoxON, for: .selected)
          }
      }
      
    • Add unique tags to the buttons (optional).

    • Create one IBAction and connect all buttons to the action
    • Use a switch statement to distinguish the buttons by index in the array or by tag

      @IBAction func boxTouched(_ sender: UIButton) {
          sender.isSelected = !sender.isSelected
          let index = boxes.index(of: sender)!
          switch index {
             // handle the cases
          }
      }
      
      @IBAction func boxTouched(_ sender: UIButton) {
          sender.isSelected = !sender.isSelected
          switch sender.tag {
             // handle the cases
          }
      }
      

提交回复
热议问题