【问题标题】:Why does my like button like all my images when I only liked one image?当我只喜欢一张图片时,为什么我的喜欢按钮会喜欢我所有的图片?
【发布时间】:2020-06-15 19:58:25
【问题描述】:

我的 VC 中有所有这些图像的集合视图。当我点击其中一个时,另一个 VC 会打开,我可以点击一个按钮来喜欢由按钮更改其图像所指示的图像。我遇到的问题是所有其他图像也都在改变。我如何特别喜欢我点击的一张图片而不是所有图片。这是我正在使用的代码:

 //First VC

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as!
    CustomCollectionViewCell

    //shows text
    cell.nameLbl.text = heroes[indexPath.row].localized_name.capitalized
    cell.nameLbl.adjustsFontSizeToFitWidth = true

    //shows images
    let defaultLink = "https://api.opendota.com"
    let completeLink = defaultLink + heroes[indexPath.row].img

    print("This is my\(completeLink)")


    cell.imageView.downloaded(from: completeLink)
    cell.imageView.isUserInteractionEnabled = true


    //shows the num of how many heroes there are
    let heroCount = heroes.count
    howManyHerosLabel.text = String(describing: heroCount)

    return cell
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {



    let completeLink = defaultLink + heroes[indexPath.item].img//this will return the exact string for selected cell

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewController") as! HeroViewController

    secondViewController.completeLink2 = completeLink
    secondViewController.completeLink3 = heroes[indexPath.item].localized_name.capitalized

    self.present(secondViewController, animated: true, completion: nil)

    print("the title of the image is \(completeLink)")
 }



    //Second VC
    override func viewDidLoad() {
    super.viewDidLoad()


    if UserDefaults.standard.bool(forKey: "Change") {

    likedButton.setImage(UIImage(named: "selected_star"), for: .normal)

    }


    //returns image and text that was presssed on in the VC
    heroImageView2.downloaded(from: completeLink2)
    labelForHero!.text = completeLink3


    }



    @IBAction func addToLikes(_ sender: Any) {
    //progressView.isHidden = false

    UserDefaults.standard.set(true, forKey: "Change")
    likedButton.setImage(UIImage(named: "selected_star"), for: .normal)

    }

【问题讨论】:

  • 请出示您的cellForItemAt
  • 我添加了代码

标签: swift uicollectionview uikit


【解决方案1】:

你需要有唯一的值来确定它是喜欢还是不喜欢

UserDefaults.standard.set(true, forKey: "Change")

现在..您正在检查更改...一旦设置为 true 将保持 true ... 我的建议是将heroes[indexPath.item].img 传递给其他控制器并针对此值设置 UserDefault

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-20
    • 2014-09-21
    • 2016-04-04
    • 2019-07-03
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多