Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change button image in swift?

I am working on an app which has a button. The button has no text, image or background.

So what I want to do is to give it an image in the viewDidLoad function.

This is what I have:

@IBOutlet var tapButton: UIButton!

override func viewDidLoad() {

    super.viewDidLoad()

    tapButton.setImage("redTap.png", forState: UIControlState.Normal)
}

But I have an error that says I can not convert string to UIIMage.

How do I get it to work?

I have tried:

let image = UIImage(named: "redTap.png")

tapButton.setImage(image, forState: UIControlState.Normal)

I have gotten it to work but now I have a problem.

The image is suppose to be a red text but it shows up blue.

I was able to get the image to show correctly by using:

let image = UIImage(named: imageColor[randNum])?.imageWithRenderingMode(.AlwaysOriginal)
tapButton.setImage(image, forState: UIControlState.Normal)

What I want now is to not have the button be highlighted when the button is pressed. I have a few other buttons that have images assigned to them in xcode and not through code. They don't highlight when pressed.

So how can I get rid of highlighting when the button is pressed?

like image 698
user2303213 Avatar asked Jun 26 '16 18:06

user2303213


People also ask

How do I resize a button image in Swift?

Using storyboard, select the button, then in the size inspect click the dropdown on size just above Content inset. There is a list of sizes to select from, and this will adjust your image size(if you use system image). The default size is already set when you added the button on the storyboard to the View Controller.

How do I change the color of a button image in Swift?

If you are setting the image for a button, just go to attributes inspector and change the button type to system. Then set the image and change the tint color. The color of the image will change.

What is Uiimage?

An object that manages image data in your app.

How do I use buttons in SwiftUI?

SwiftUI's button is similar to UIButton , except it's more flexible in terms of what content it shows and it uses a closure for its action rather than the old target/action system. To create a button with a string title you would start with code like this: Button("Button title") { print("Button tapped!") }


1 Answers

You don't need ".png".

If ".imageWithRenderingMode(.AlwaysOriginal)" is working for you: To keep the same image in different states, you have to set the same image/properties for the different states.

@IBOutlet var tapButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
    tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Highlighted)
}
like image 181
Meagan S. Avatar answered Oct 10 '22 13:10

Meagan S.