【发布时间】:2022-02-02 10:45:11
【问题描述】:
当数组中的不同项目显示在标签中时,我有一个按钮可以更改图像。我希望按钮图像在选择按钮时更改为不同的图像。如何以编程方式执行此操作?我尝试了 button1.setImage(UIImage(named: "GreenHeart"), for: .selected),但这似乎不起作用(图像只是停留在 Heart)。出于某种原因,如果我使用 .highlighted 而不是 .selected 一切正常(我可以看到 GreenHeart 图像)。不确定这是否有帮助,但我是编码新手,所以我想我会在这里添加它以获得更多支持。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var quotesLabel: UILabel!
var firstQuote = -1
var quotes = ["The best time to plant a tree was 20 years ago - The next best time is today - Unknown",
"Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe",
"Buy less, choose well, make it last - Vivienne Westwood",
"The future depends on what we do in the present - Mahatma Gandhi",
]
@IBAction func nextButton(_ sender: Any) {
if firstQuote < quotes.count{
firstQuote = (firstQuote + 1) % quotes.count
quotesLabel.text = quotes[firstQuote]
}
let quote1 = "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"
let quote2 = "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe"
let quote = quotesLabel.text
let view1 = UIView()
view.addSubview(view1)
view1.frame = CGRect(x: 100, y: 500, width: 200, height: 100)
view1.backgroundColor = .clear
let button1 = UIButton(type: .custom)
button1.setImage(UIImage(named: "Heart"), for: .normal)
button1.setImage(UIImage(named: "GreenHeart"), for: .selected)
view1.addSubview(button1)
button1.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
button1.isHidden = true
if quote == quote1{
button1.isHidden = false
} else {
button1.isHidden = true
}
let button2 = UIButton(type: .custom)
button2.setImage(UIImage(named: "GreenHeart"), for: .normal)
view1.addSubview(button2)
button2.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
button2.isHidden = true
if quote == quote2{
button2.isHidden = false
} else {
button2.isHidden = true
}
}
}
【问题讨论】:
-
"我希望按钮图像在选择按钮时更改为不同的图像。"选择按钮 的代码部分在哪里?
标签: swift image button selected