When using UIButton.Configuration it's impossible to limit number of lines of the button's title label

Up until iOS 15 it was possible to set maximum number of lines of the UIButton titleLabel property, but when UIButton.Configuration is used to configure button's properties setting the titleLabel?.numberOfLines to any value is always ignored and reset after assigning text to configuration.

See the short piece of code below:

import UIKit

let button = UIButton(configuration: .plain())

button.titleLabel?.numberOfLines = 1

print("Lines: \(button.titleLabel?.numberOfLines ?? 999)") // <- prints "Lines: 1"

var buttonConfiguration = button.configuration

buttonConfiguration?.title = "Any text"

button.configuration = buttonConfiguration

print("Lines: \(button.titleLabel?.numberOfLines ?? 999)") // <- prints "Lines: 0"

Even if you set the numberOfLines to 1 it is ignored and the button renders one, or more lines of text.

I think it's a bug, there is no compiler warning about accessing the titleLabel property, as there is with imageEdgeInsets for example. If you access that one Xcode gives you a warning

'imageEdgeInsets' was deprecated in iOS 15.0: This property is ignored when using UIButtonConfiguration

If modifying titleLabel directly there should be a warning as well, but if that's the case, the UIButton.Configuration is seriously lacking some features, like setting maximum number of lines, or even a font (this can be done via AttributedString but setting font is so common that constructing AttrbitutedString every time the title is changed feels so wrong and unnecessary)

For the time being I'm forced to use the legacy button customisation

  • Bumping this up, I think this is still an issue. Is there any way around this? If we use attributedString, how do set number of lines?

Add a Comment

Replies

I'm also running into this issue, setting the UIButton's .configuration property prevents us from having a single line button with a truncated tail.

If you are using Button.Configuration, then to limit the number of rows to 1 you need to do the following:

var conf = UIButton.Configuration.plain()
conf.titleLineBreakMode = .byTruncatingTail
let button = UIButton(configuration: conf)
  • in addition to this

    the doc says

    Default is WordWrapping. WordWrapping and CharWrapping both allow for multi-line text, other modes will restrict the title to a single line of text.

    be aware, the titleLineBreakMode property is actually available starting from Xcode 14.3

Add a Comment