swiftuikituibuttonios15

How to remake UIButton to use UIButton.Configuration


In the context of updating legacy code to modern standards, I have encountered a scenario where I need to refactor a UIButton creation and configuration process. The original implementation is as follows:

let button = UIButton()
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
button.setImage(UIImage(named: "MyIcon"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: -8, left: -40, bottom: -8, right: 0)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.translatesAutoresizingMaskIntoConstraints = false
button.sizeToFit()

I would appreciate guidance on transitioning this code to use the UIButton.Configuration paradigm introduced in iOS 15, ensuring that the visual layout and interaction behaviors of the button remain consistent with the original implementation. What approach or specific configurations would be required to achieve this?


Solution

  • I'd suggest to add an image of the button to make it easier to create the code but based on what you explained...

    iOS 15.0+

    UIButton.Configuration contains all the customization options available with other methods, such as setTitle(_:for:), and can serve as a replacement for all those methods you provided.

        let button = UIButton(type: .system)
        button.translatesAutoresizingMaskIntoConstraints = false
        
        var configuration = UIButton.Configuration.filled()
        
        configuration.baseBackgroundColor = .link // color of the button background
        configuration.baseForegroundColor = .white // color of the text and image
        
        configuration.image = UIImage(systemName: "star")
        
        configuration.title = "Star Button"
        
        configuration.imagePlacement = .leading
        configuration.contentInsets.leading = 40
        configuration.imagePadding = 20
        
        configuration.titlePadding = 20 // 20 starting from the end of the image
        
        button.configuration = configuration
        
        button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
    

    Button screenshot

    I'd highly suggest you to take a look at those sites as they have examples on most of the cases:

    UseYourLoaf UIButton.Configuration

    Sarunw UIButton.Configuration