如何快速更改按钮图像? [英] How to change button image in swift?

查看:29
本文介绍了如何快速更改按钮图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有按钮的应用.该按钮没有文本、图像或背景.

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

所以我想做的是在 viewDidLoad 函数中给它一个图像.

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

这就是我所拥有的:

@IBOutlet var tapButton: UIButton!

override func viewDidLoad() {

    super.viewDidLoad()

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

但我有一个错误,提示我无法将字符串转换为 UIIMage.

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

我如何让它工作?

我试过了:

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)

我现在想要的是在按下按钮时不突出显示按钮.我还有一些其他按钮,它们在 xcode 中而不是通过代码分配了图像.按下时不会突出显示.

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?

推荐答案

您不需要.png".

如果.imageWithRenderingMode(.AlwaysOriginal)"对您有用:要在不同状态下保持相同的图像,您必须为不同的状态设置相同的图像/属性.

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)
}

这篇关于如何快速更改按钮图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆