john doe
john doe

Reputation: 9660

UIButton not expanded with assigned text

I have a UIButton on the screen. There are no width constraints on the UIButton. I like my UIButton to be expanded to the assigned text. But here is the result:

enter image description here

Here is the implementation:

self.translatedPhraseButton.setTitle(self.selectedPhrase.translatedPhrase, for: .normal)
self.translatedPhraseButton.sizeToFit()
self.translatedPhraseButton.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
self.translatedPhraseButton.layer.cornerRadius = 10.0
self.translatedPhraseButton.layer.masksToBounds = true
self.translatedPhraseButton.backgroundColor = UIColor(fromHexString: "2aace3")

Upvotes: 2

Views: 2658

Answers (3)

john doe
john doe

Reputation: 9660

So, I finally resolved my issue by using a single line of code:

 self.translatedPhraseButton.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 0.0, right: 15.0) 

Upvotes: 5

user1046037
user1046037

Reputation: 17695

Problem:

The reason why the text gets truncated is because of the following line:

self.translatedPhraseButton.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)

You have added 10.0 padding to the title label, which causes the text to truncate.

Solution:

I have used Swift 3 (It wouldn't be hard to change it to Swift 2 if you need)

Button:

class RoundedCornerButton : UIButton {

    override func draw(_ rect: CGRect) {

        let path = UIBezierPath(roundedRect: rect,
                                byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight],
                                cornerRadii: CGSize(width: 10, height: 10))

        UIColor.red.setFill()

        path.fill()
    }

    override var intrinsicContentSize: CGSize {

        let originalSize = super.intrinsicContentSize

        let size = CGSize(width: originalSize.width + 10, height: originalSize.height)

        return size
    }
}

Invoking:

let translatedPhraseButton = RoundedCornerButton()
translatedPhraseButton.setTitle("haskjhdjk", for: .normal)

view.addSubview(translatedPhraseButton)

translatedPhraseButton.translatesAutoresizingMaskIntoConstraints = false

translatedPhraseButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
translatedPhraseButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Upvotes: 2

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7736

Try creating a temporary label, then setting the button's size to that label's.

let label = UILabel()
label.text = button.titleLabel?.text
label.font = button.titleLabel?.font
label.sizeToFit()

yourButton.frame.size = label.frame.size

Also, you can adjust the button's titleLabel to shrink the text to have it fit:

button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.5

Upvotes: 2

Related Questions