我是swift的新手。我有一个按钮和3个图像保存在阵列中。我想要的是通过单击按钮更改图像。
let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {
}
答案 0 :(得分:0)
let image = UIImage(named: circleArray[0]) // circleArray[1], circleArray[2]
在你的动作功能设置按钮图像
中button.setImage(image, for: .normal)
答案 1 :(得分:0)
button.setImage(UIImage(named: circleArray[0]),forState:Normal)
您可以为按钮的各种状态设置各种图像(例如,标准,突出显示,选中)
这是你要找的东西吗?如果您正在寻找其他内容,请详细说明。
答案 2 :(得分:0)
Swift 3.0
全班宣言,
let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
var index = 0
UIImageView
:
@IBOutlet var imageView: UIImageView! //Global
@IBAction func carbsButton(_ sender: Any) {
self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
self.imageView.image = UIImage(named:circleArray[index])
}
UIButton
将Any
中的carbsButton(_ sender: Any)
更改为carbsButton(_ sender: UIButton)
。完成以下代码后,
@IBAction func carbsButton(_ sender: UIButton) {
self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
sender.setImage(UIImage(named:circleArray[index]), for: .normal)//Button
}
UIImageView and UIButton
:
let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
var index = 0
@IBOutlet var imageView: UIImageView!
@IBAction func carbsButton(_ sender: UIButton) {
self.index = (self.index >= self.circleArray.count-1) ? 0 : self.index+1
self.imageView.image = UIImage(named:circleArray[index]) //imageView
sender.setImage(UIImage(named:circleArray[index]), for: .normal)//Button
}
示例输出:
sender.setBackgroundImage(UIImage(named:circleArray[index]), for: .normal)
答案 3 :(得分:0)
首先,您需要为UIButton提供标签
@IBOutlet var btn: UIButton!
let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
override func viewDidLoad() {
super.viewDidLoad()
see.btn.tag = 0
}
@IBAction func carbsButton(_ sender: Any) {
button.setImage(UIImage(named: circleArray[btn.tag % 3]),forState:Normal)
btn.tag = ban.tag + 1
}
以这种方式,你一定会得到你想要的东西。如果它解决了问题,请点击箭头。