Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set an image/icon on button in Swift

I am trying to achieve something like this:

enter image description here

So I want to add an image on the left of my button's title.

I have found the following paragraph in documentation:

enter image description here

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

like image 559
Almazini Avatar asked Sep 06 '25 03:09

Almazini


2 Answers

You should correctly set up the edge insets for the button items.

You can find the IB properties here:

enter image description here

Programmatically, you can setup edge insets as below:

 [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
 [button setImageEdgeInsets:UIEdgeInsetsMake(0, -70, 0, 0)];

UPD:

enter image description here

like image 106
CheshireKat Avatar answered Sep 07 '25 20:09

CheshireKat


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.

like image 31
Suciu Radu Avatar answered Sep 07 '25 20:09

Suciu Radu