Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton Configuration Line Break Mode Not Working

I know there are a few SO posts about this, but none are working...

I am just trying to get my custom UIButton subclass using the UIButton.Configuration method to force my title label to stay 1 line, without changing the button frame.

I keep getting the right button shown below...

enter image description here

What can I do?? Here is how I am setting up by button..

init(withTitle title: String, ... <more custom params> ...) {

    // ...

    super.init(frame: .zero)

    var config = UIButton.Configuration.filled()
    config.title = title

    titleLabel?.lineBreakMode = .byTruncatingTail
    titleLabel?.numberOfLines = 1
                
    configurationUpdateHandler = { button in

        // ... here I handle colorizing elements for different button states /

    }

}

I understand I can accomplish the text clipping by using a standard let button = UIButton(type: .custom), and set the titleLabel line properties. This is not a solution - the customization offered with the configuration are not available otherwise.

like image 884
Will Von Ullrich Avatar asked Nov 02 '25 05:11

Will Von Ullrich


1 Answers

One big issue with your code is that you create the UIButton.Configuration but you never make use of it. Here's an updated version of your custom init for your custom UIButton subclass that properly sets up and uses a UIButton.Configuration.

class MyButton: UIButton {
    convenience init(withTitle title: String, image: String) {
        var config = UIButton.Configuration.filled()
        config.title = title
        config.titleLineBreakMode = .byTruncatingTail
        config.image = UIImage(systemName: image)

        self.init(configuration: config)

        configurationUpdateHandler = { button in
            // ... here I handle colorizing elements for different button states
        }
    }
}

By making the custom init a convenience init, you can call the init(configuration:) convenience init.

Add that class and the following code to an iOS Swift Playground:

let btn = MyButton(withTitle: "This is some sample text that should CLIP", image: "calendar")
btn.frame = CGRect(x: 0, y: 0, width: 150, height: 50)

and you get the following result:

enter image description here

Obviously you need to adjust this sample code with your additional init parameters and button configuration.

like image 119
HangarRash Avatar answered Nov 04 '25 19:11

HangarRash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!