Home > Software design >  iOS 15 UIButton configuration - how to write a closure for configuration handler
iOS 15 UIButton configuration - how to write a closure for configuration handler

Time:12-17

Following a tutorial I am using a the new UIButtons and iOS 15.

    let btn = UIButton(frame:CGRect(x: 25, y:0 , width: 250, height: 50))
    btn.config.title = "Connect"
    btn.updateConfiguration()
    btn.configurationUpdateHandler = { button in
      var config = btn.configuration
        switch button.state {
        case .highlighted:
            config?.showsActivityIndicator = true
            config?.imagePadding = 5
            self.role = self.nameInput.text?.lowercased()
            UserDefaults.standard.set(self.role, forKey: "role")
            SFSConn.shared.connect()
        default:
            config?.showsActivityIndicator = false
        }
      btn.configuration = config
    }
    btnForm.addSubview(btn)

How can I extrapolate the closure into a stand-alone closure? I'd like to connect multiple buttons to the same closure. Thanks in advance.

CodePudding user response:

The configurationUpdateHandler property is of type UIButton.ConfigurationUpdateHandler?, which is just a typealias for (UIButton) -> Void, which is a closure that takes a single parameter of UIButton. So just create that.

let handler: (UIButton) -> Void = { (button) in
    // do something
}

btn.configurationUpdateHandler = handler
  • Related