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...

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.
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:

Obviously you need to adjust this sample code with your additional init parameters and button configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With