0

I am creating a sample app which has some texts on UIButton and also image, for image and text are subView of UIButton. I have run with different devices like iPhone 5 , iPhone X and the result not like what i expected because if run with device which its screen smaller than iPhone X then the text will be floating outside the button.

What i have done so far:

lazy var myLabelButton: UILabel = {

    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "titleName"
    label.textColor = .white
    label.font = UIFont(name: "SFCompactText-Regular", size: 14)
    label.adjustsFontSizeToFitWidth = true
    label.minimumScaleFactor = 0.5
    label.sizeToFit()
    return label
}()

I searched for some resources and they let me apply these functions:

label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.sizeToFit()

Those above three functions are not work

Here is the whole code:

button.addSubview(myLabelButton)
NSLayoutConstraint.activate([
  myLabelButton.centerXAnchor.constraint(button.centerXAnchor),
  myLabelButton.centerYAnchor.constraint(button.centerYAnchor),
  myLabelButton.widthAnchor.constraint(button.widthAnchor)
])

Any solution for this?

Visal Sambo
  • 1,270
  • 1
  • 19
  • 33

2 Answers2

0

Try using sizeToFit() on the button itself, not the label.

For example

button.setTitle("Hello world", for: .normal)
button.sizeToFit()
Gismay
  • 784
  • 9
  • 17
0

Here you go, i have the solution

    let label = UILabel()
    label.numberOfLines = 0
    label.textColor = .white

    let button = UIButton()
    button.backgroundColor = .blue

    view.addSubview(button)
    button.addSubview(label)

    label.text = Array(repeating: "Hello", count: 100).joined()

    button.translatesAutoresizingMaskIntoConstraints = false
    label.translatesAutoresizingMaskIntoConstraints = false

    // button constraint
    NSLayoutConstraint.activate([
        view.leadingAnchor.constraint(equalTo: button.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: button.trailingAnchor),
        view.centerYAnchor.constraint(equalTo: button.centerYAnchor)
    ])


    // label constaint
    NSLayoutConstraint.activate([
        button.leadingAnchor.constraint(equalTo: label.leadingAnchor),
        button.trailingAnchor.constraint(equalTo: label.trailingAnchor),
        button.topAnchor.constraint(equalTo: label.topAnchor),
        button.bottomAnchor.constraint(equalTo: label.bottomAnchor)
    ])

label image

Salman500
  • 1,213
  • 1
  • 17
  • 35