I need a button with an image inside of it and a text under the button. I can't use the image as a background because it would stretch the image. So my problem is if I use an image for the button, the title will be covered by the image. Is there any solution for this?
Here is an example how it should look like at the end:
Change Title and Image Insets
also change control Vertical to bottom
You could make a separate UIImage and UILabel at the positions you prefer, and cover them with transparent UIButton.
That should do the trick.
Hope it helps.
You have two options
1) Create UIView add Image , label and button
2) You can to set Title And Image inset , You can do it in XIB easily
For option two I have added simple example , (Replace it with your value)
You can subclass UIButton and redefine layoutSubviews method.
You can adjust the following properties of UIButton
: var titleEdgeInsets: UIEdgeInsets
, var imageEdgeInsets: UIEdgeInsets
.
Another way of doing this is subclassing UIControl
. It's a UIView
subclass that is meant to be used for such cases. UIButton
is a subclass of UIControl
for example. That way you have more control over the layout and you don't need to fight UIButton
's builtin behaviour.
You can do your layout either in code or with Interface Builder in a xib
file.
class MyButton: UIControl {
var imageView: UIImageView
var label: UILabel
// adjust colors for changed states like highlighting, etc.
override var isHighlighted: Bool {
didSet {
if isHighlighted {
backgroundColor = UIColor.grey
} else {
backgroundColor = UIColor.white
}
}
}
override var isSelected: Bool { didSet { ... } }
override var isEnabled: Bool { didSet { ... } }
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
imageView = UIImageView(image: UIImage(...))
addSubView(imageView)
label = UILabel(frame: CGRect(...))
addSubView(label)
// TODO: add constraints for layout
}
}