【发布时间】:2020-10-01 22:32:28
【问题描述】:
我是编码新手,所以请原谅我乱七八糟的代码。我正在尝试在点击该按钮时更改该按钮的图像。该按钮位于 UICollectionViewCell 中,这使得这有点棘手。
这是按钮被添加到单元格的地方:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let d = self.data[indexPath.row].image
let button = UIButton(frame: CGRect(x:0, y:0, width:68,height:80))
button.setImage(d, for: UIControl.State.normal)
button.addTarget(self, action: #selector(buttonTapped), for: UIControl.Event.touchUpInside)
cell.addSubview(button)
return cell }
这是按钮从中获取图像的数据数组:
var data: [CustomData] = [CustomData]()
override func viewDidLoad() {
super.viewDidLoad()
self.data.append(CustomData(title: "abc", image: #imageLiteral(resourceName: "bookOne"), url: "typeURLa"))
self.data.append(CustomData(title: "def", image: #imageLiteral(resourceName: "bookTwo"), url: "typeURLb"))
self.data.append(CustomData(title: "ghi", image: #imageLiteral(resourceName: "bookThree"), url: "typeURLc"))
}
这是点击按钮时发生的情况:
@objc func buttonTapped(sender: UIButton!) {
print("button tapped")
let r = data[0]
print(sender.currentImage!)
print(r.image)
sender.setImage(r.image, for: UIControl.State.normal)
collectionView.reloadData()
print(sender.currentImage!)
print(r.image)
}
在调试控制台中我可以看到它确实更新了按钮图像,但在模拟器中图像保持不变。
button tapped
<UIImage:0x600000adad90 named(main: bookTwo) {600, 754}>
<UIImage:0x600000adafd0 named(main: bookOne) {798, 1210}>
<UIImage:0x600000adafd0 named(main: bookOne) {798, 1210}>
<UIImage:0x600000adafd0 named(main: bookOne) {798, 1210}>
当我点击第 2 行中包含图像“bookTwo”的按钮时,我希望它更改为图像“bookOne”。当我在点击后打印出第 2 行中按钮的图像时,我可以看到它在调试控制台中成功地将“bookTwo”更改为“bookOne”图像。 “bookOne”位于数组 data[0] 中,“bookTwo”位于 data[1] 中。但屏幕上仍然显示图像“bookTwo”。
【问题讨论】:
-
你的备用图片名称是什么
-
@Anbu.Karthik 对不起,你的意思是什么?
-
它是您的主图像右侧“bookOne”、“bookTwo”、“bookThree”,例如您选择“bookOne”按钮要替换的图像。
-
@Anbu.Karthik 当我点击第 2 行中包含图像“bookTwo”的按钮时,我希望它更改为图像“bookOne”。当我在点击后打印出第 2 行中的按钮图像时,我可以看到它在调试控制台中成功地将“bookTwo”更改为“bookOne”图像。 “bookOne”位于数组 data[0] 中,“bookTwo”位于 data[1] 中。但屏幕上仍然显示图像“bookTwo”。
标签: ios swift xcode uicollectionview uibutton