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?
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.
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.
An object that manages image data in your app.
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!") }
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)
}
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