Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the icon on the button in ios using Swift?

I want to use the icon on the button in IOS using Swift, just like the icons on the buttons in the Android. Is there any way without setting the image or without fontAwesome icon to set icon on the button?

like image 836
Lovish Avatar asked Mar 30 '16 07:03

Lovish


People also ask

How do I toggle a button in Swift?

How do you toggle a button in Swift? You can create a toggle or switch by simply typing Toggle() . To configure toggle, we have to pass the parameter. The parameter name is isOn of type Binding<Bool> , which defines the state of the toggle (i.e., whether it's on or off).

How do I make a button in Swift app?

You can do this by holding Option on your keyboard and clicking the ViewController. swift file in your Project Navigator. Now click on the button, hold CTRL and then drag it to your Swift file. This will open an IBOutlet dialog.


2 Answers

Via code in Swift 3 and Swift 4:

yourButton.setImage(UIImage(named: "imgName"), for: .normal)

or for the background image:

yourButton.setBackgroundImage(UIImage(named: "imgName"), for: .normal)

Via storyboard:

You can also set the icon for a button via the storyboard, setting the image in the attributes inspector of a button element. If you want to have a title over your image set your image in background of the attribute inspector

enter image description here

Question from the comments

how do you put the image alongside the "button" text?

You can do that via code for example by setting the imageEdgeInsets of the button. The example below places the image to the right from the text

yourButton.setImage(UIImage(named: “imgNameWhichYouWantToSetAlongsideTheButton"), for: .normal)
yourButton.imageEdgeInsets = UIEdgeInsets(top: 3, left: 0, bottom: 0, right: -8)
like image 152
ronatory Avatar answered Sep 28 '22 16:09

ronatory


enter image description here

    let icon = UIImage(named: "bmiCalculator")!
    button.setImage(icon, for: .normal)
    button.imageView?.contentMode = .scaleAspectFit
    button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)

UIEdgeInsets

The inset distances for views. Edge inset values are applied to a rectangle to shrink or expand the area represented by that rectangle. Typically, edge insets are used during view layout to modify the view’s frame. Positive values cause the frame to be inset (or shrunk) by the specified amount. Negative values cause the frame to be outset (or expanded) by the specified amount.

like image 28
Nazmul Hasan Avatar answered Sep 28 '22 15:09

Nazmul Hasan