iosswiftautolayout

Why is a button with an image in it making the titleLable text cut off?


I have this code below which creates a button in code and centers the button in the middle of its superview:

let cameraButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "cam"), for: .normal)
        button.setTitle("Take Pic", for: .normal)
        button.setTitleColor(UIColor.black, for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
        return button
}()

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        view.addSubview(cameraButton)
        cameraButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        cameraButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}

Everything is working fine (as in the button is being centered in the center of the view) but the titleLabel text is being cut off for some reason (shown in the picture below):

enter image description here

I thought buttons have an intrinsic width and height so why would the titleLabel be cut off here? Shouldn't the width just expand based on the content inside of it (the imageView as well as the label)? Can someone advise me a way to fix this?


Solution

  • Try with setting below attributes

    cameraButton.titleLabel!.numberOfLines = 0
    cameraButton.titleLabel!.adjustsFontSizeToFitWidth = true
    cameraButton.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping