I am trying to achieve something like this:
So I want to add an image on the left of my button's title.
I have found the following paragraph in documentation:
button.currentImage is read only property and I can not set it. Who can tell how to implement it?
I was trying to do it like this:
private let logoButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("Logo", for: .normal)
button.setImage(UIImage(named:"logo"), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(handleLogo), for: .touchUpInside)
return button
}()
But unfortunately I get picture stretched inside button and no title ...
Am I missing something? Or should I try creating custom view with image + lable and make it clickable? thanks
You should correctly set up the edge insets for the button items.
You can find the IB properties here:
Programmatically, you can setup edge insets as below:
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -70, 0, 0)];
UPD:
A good method will be to create a UIView
with the dimensions you want, then set a UIImage
inside it, set it to AspectFit (or whatever you want) and then also set the UILabel
you need. This will let you customize a lot more the view than you can do with a UIButton
. Also you need to connect a UITapGestureRecognizer
on the view, like this:
override func viewDidLoad() {
super.viewDidLoad()
logoView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(logoViewClicked)))
}
@objc func logoViewClicked() {
//handle code here
}
I prefer it this way, as I said, have more space to customize things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With