Search code examples
swiftuibuttoniboutletcollection

select one item in an outlet collection - swift


How would I code: select the button who's titlelabel.text is equal to "category"

@IBOutlet var buttons: [UIButton]!

var category: String?

  override func viewDidLoad() {
    super.viewdidload()

      //I want to put the code here!

    }

Solution

  • Here is how you can filter out that button

    let requiredButton = buttons
            .filter{ $0.titleLabel?.text == "category" }.first
    

    Also you can achieve that with first

    let butt =   buttons.first(where: { $0.titleLabel?.text == "category" })