Reputation: 6752
I want to make a button which has an icon and a label on the bottom of it so like this:
What would be the best way to do this? Is it possible to drag an image view object and a label into a button?
Upvotes: 6
Views: 7939
Reputation: 1358
Cleaned up @Shahzaib Maqbool's answer. I had some crashes originally, fixed those by removing the force unwrapping. Tested on Swift 5.
extension UIButton {
func alignTextBelow(spacing: CGFloat = 6.0) {
guard let image = self.imageView?.image else {
return
}
guard let titleLabel = self.titleLabel else {
return
}
guard let titleText = titleLabel.text else {
return
}
let titleSize = titleText.size(withAttributes: [
NSAttributedString.Key.font: titleLabel.font
])
titleEdgeInsets = UIEdgeInsets(top: spacing, left: -image.size.width, bottom: -image.size.height, right: 0)
imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0, bottom: 0, right: -titleSize.width)
}
}
Upvotes: 4
Reputation: 1487
By code you can do it like this Swift 4.2 compatible code is here , you just need to call function
public extension UIButton
{
func alignTextBelow(spacing: CGFloat = 6.0)
{
if let image = self.imageView?.image
{
let imageSize: CGSize = image.size
self.titleEdgeInsets = UIEdgeInsets(top: spacing, left: -imageSize.width, bottom: -(imageSize.height), right: 0.0)
let labelString = NSString(string: self.titleLabel!.text!)
let titleSize = labelString.size(withAttributes: [NSAttributedString.Key.font: self.titleLabel!.font])
self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
}
}
}
Upvotes: 12
Reputation: 5680
UIButton has two properties you may find of interest. They are titleEdgeInsets and imageEdgeInsets.
Use this property to resize and reposition the effective drawing rectangle for the button title. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge
You could play around with these to get your desired layout.
Upvotes: 1