Reputation: 9660
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:
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
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
Reputation: 17695
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.
I have used Swift 3 (It wouldn't be hard to change it to Swift 2 if you need)
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
}
}
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
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