简体   繁体   English

Swift:UICollectionViewCell 中的 UIButton 图像不会改变

[英]Swift: UIButton image in UICollectionViewCell won't change

I'm new to coding so please excuse me for my messy code.我是编码新手,所以请原谅我乱七八糟的代码。 I'm trying to change the image of a button when that button is tapped.我正在尝试在点击该按钮时更改该按钮的图像。 The button is located in a UICollectionViewCell which makes this a bit tricky.该按钮位于 UICollectionViewCell 这使得这有点棘手。

This is where the button gets added to the cell:这是按钮被添加到单元格的地方:

    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 }

This is the data array where the button gets its image from:这是按钮从中获取图像的数据数组:

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

This is what happens when the button gets tapped:这是点击按钮时发生的情况:

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


        }

In the debug console I can see it did update the button image yet in the simulator the image stays the same.在调试控制台中,我可以看到它确实更新了按钮图像,但在模拟器中图像保持不变。

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

When I tap the button in row 2 that holds the image "bookTwo" I want it to change to the image "bookOne".当我点击第 2 行中包含图像“bookTwo”的按钮时,我希望它更改为图像“bookOne”。 When I print out the image of the button in row 2 after it got tapped, I can see it successfully changed "bookTwo" into "bookOne" image in the debug console.当我在点击后打印出第 2 行中按钮的图像时,我可以看到它在调试控制台中成功地将“bookTwo”更改为“bookOne”图像。 "bookOne" located in the array data[0] and "bookTwo" located in data[1]. “bookOne”位于数组 data[0] 中,“bookTwo”位于 data[1] 中。 But on screen the image "bookTwo" still shows.但是屏幕上仍然显示图像“bookTwo”。

The problem is you have been reloading collectionView every time after the cell has been updated.问题是您每次更新单元格后都在重新加载collectionView。 Whenever you reload collectionView collectionViewCellForItemAt method is being called.每当您重新加载 collectionView 时,都会调用 collectionViewCellForItemAt 方法。 But in collectionViewCellForItemAt the method had been set to write the image in button as the image in the indexpath.row of the data array.但是在collectionViewCellForItemAt 方法中已经设置了将按钮中的图像写入数据数组的indexpath.row 中的图像。 Since the data array is unchanged, the cell is being set back as the default image given by the data array.由于数据数组未更改,因此将单元格设置为数据数组给出的默认图像。

Instead you can update the code.相反,您可以更新代码。 The updated code looks like this更新后的代码如下所示

@objc func buttonTapped(sender: UIButton!) {
            print("button tapped")
            let row = sender.tag
            let intialData = data[row]

            print(sender.currentImage!)
            print(data[row].image)

            data[row] = CustomData(title: intialData.title, image: #imageLiteral(resourceName: "bookOne"), url: intialData.url)

            sender.setImage(data[row].image, for: UIControl.State.normal)

            print(sender.currentImage!)
            print(data[row].image)
        }

In collectionViewCellForItemAt add this line button.tag = indexPath.row.在 collectionViewCellForItemAt 添加这一行 button.tag = indexPath.row。 The updated code looks like this更新后的代码如下所示

    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.tag = indexPath.row
    button.addTarget(self, action: #selector(buttonTapped), for: UIControl.Event.touchUpInside)
    cell.addSubview(button)

    return cell 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM