Swift - stop truncating UIButton titleLabel

563 views Asked by At

I have the following UIButton defined:

internal lazy var volumeUnitSelector: DropDownButton = {

    let button = DropDownButton()
    button.setTitle("impg", for: .normal)
    button.setTitleColor(UIColor.darkGreyWithDarkMode.withAlphaComponent(0.7), for: .normal)
    
    button.titleLabel?.font = .systemFont(ofSize: 14)
    button.titleLabel?.textAlignment = .right
    
    if #available(iOS 13.0, *) {
        let config = UIImage.SymbolConfiguration(pointSize: 8, weight: .black)
        let symbol = UIImage(systemName: "arrowtriangle.down.fill", withConfiguration: config)?.withTintColor(UIColor.darkGreyWithDarkMode, renderingMode: .alwaysOriginal)
        button.setImage(symbol, for: .normal)
    }
    return button
}()

And here is the DropDownButton class which subclasses UIButton:

class DropDownButton: UIButton {

    override func layoutSubviews() {
        self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 9)    

        super.layoutSubviews()
        if imageView != nil {

            imageView?.translatesAutoresizingMaskIntoConstraints = false
            imageView?.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
            imageView?.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
            self.widthAnchor.constraint(equalToConstant: 43).isActive = true
        }
    }
}

Here's the challenge - I'm trying to set this button to have the text 'impg' and then an arrow to indicate a drop down menu to the right of the text. So as you can see, I've added the arrow as an SFSymbol and pinned it to the right of the button. I then need me text to be essentially pinned to the leadingAnchor of the arrow image, with a small margin (0.5 / 1 point).

So, I've set the titleEdgeInset to 9 on the right hand side to make room for the image. Now this is kind of working, but what I don't understand is that my title is being clipped, when there should be plenty of room for it.

Here is the current effect it has:

enter image description here

And here is the xCode layout view:

enter image description here

I don't understand why there's not enough space here to the left of the text to expand into. I have no other constraints set.

1

There are 1 answers

0
Arjun_iOS On BEST ANSWER

This is because you added the below line in your code:

self.widthAnchor.constraint(equalToConstant: 43).isActive = true

which sets the width of the button and not the image as it is self.widthAnchor and here self means UIButton.