本文介绍了尝试创建收藏夹按钮以添加收藏列表中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在CollectionViewCell上创建收藏夹按钮以保存收藏列表中的项目。当我点击收藏夹图标按钮时,它成功地将所选单元格项目添加到收藏列表类的数组中,并且还显示在收藏夹列表中。当我点击收藏夹按钮时,它会根据已保存或未保存的值更改其图像。
当我试图在NSUserDefaults中保存喜欢的列表数组时,它保存并在我检索它时显示值。但是,当我从模拟器关闭我的应用程序并再次运行时,它不显示我在NSUserDefaults中保存的收藏列表数组中的值,并且还希望根据已添加或未添加的项目设置按钮图像状态。

I'm trying to create favorite button on CollectionViewCell for saving items in favorite list. When i tapped on favorite icon button it successfully add selected cell item in array of favorite list class, and also shows in favorite list. When i tapped on favorite button it change its image according to values are already saved or not.When i'm trying to save favorite list array in NSUserDefaults it save and also show values when i retrieve it. But when i close my app from simulator and run again it not shows values in favorite list array that i saved in NSUserDefaults and also want to set button image state according to item already add or not.

当我点击收藏夹时。关闭我的应用程序后再次运行。
谁能告诉我如何解决这个问题。或者任何人都可以在我的项目中修复它。
谢谢

Output When i tapped on favorite. And run again after closing my App.Can anyone tell me how i can fix that. Or can anyone please fix it in my project.Thanks

import UIKit

var url : [NSString] = [
    "https://www.youtube.com/watch?v=9h30Bx4Klxg",
    "https://www.youtube.com/watch?v=ij_0p_6qTss",
    "https://www.youtube.com/watch?v=AJtDXIazrMo",
    "https://www.youtube.com/watch?v=H202k7KfZL0",
    "https://www.youtube.com/watch?v=CGyEd0aKWZE",
    "https://www.youtube.com/watch?v=AtKZKl7Bgu0",
    "https://www.youtube.com/watch?v=4SYlLi5djz0"]

var image : [NSString] = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg"]


class LiveCollectionView: UIViewController, UICollectionViewDataSource,UIWebViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(animated: Bool) {
        let value = UIInterfaceOrientation.Portrait.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return url.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! LiveCollectionViewCell

        cell.imageView.image = UIImage(named: image[indexPath.row] as String)
        cell.playBt.addTarget(self, action: Selector("webView:"), forControlEvents: UIControlEvents.TouchUpInside)

        cell.playBt.tag = indexPath.row
        cell.heartBt.tag = indexPath.row

        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    }
}







import UIKit

class LiveCollectionViewCell: UICollectionViewCell{

var showPlayButton = true

var number = Int()
var secondNumber = Int()

@IBOutlet weak var playBt: UIButton!

@IBOutlet weak var imageView: UIImageView!

@IBOutlet weak var heartBt: UIButton!

@IBAction func heartBt(sender: UIButton) {


    var btn : NSInteger
    btn = sender.tag as NSInteger

    let uValues = url[btn]
    let iValues = image[btn]

    if showPlayButton == true{
        u.append(url[btn])
        i.append(image[btn])

        self.heartBt.setImage(UIImage(named: "rheart"), forState: UIControlState.Normal)
        showPlayButton = false
        print("rHeart xxxxxxxxxxxxxxx")

    }else{

        for check in u {

            number++
            print(number)

            if uValues == check{
                print(u)
                u.removeAtIndex(number-1)
                number = 0
                print("RemoVe at indext path")
                print(u)
                break

            }

        }

        for check2 in i{

            secondNumber++
            print(secondNumber)

            if iValues == check2{
                print(i)
                i.removeAtIndex(secondNumber-1)
                secondNumber = 0
                print("RemoVe at indext path")
                print(i)
                self.heartBt.setImage(UIImage(named: "wHeart"), forState: UIControlState.Normal)
                showPlayButton = true
                print("wHeart ........")
                break

            }

        }

    }

}
}







import UIKit
var u : [NSString] = []
var i : [NSString] = []
class FavoriteTvViewController: UIViewController , UICollectionViewDelegate{
    var uV : NSArray = []
    var iV : NSArray = []

    @IBOutlet weak var collectionView: UICollectionView!

    let reuseIdentifier = "cell"

    override func viewDidLoad(){
    }

    override func viewWillAppear(animated: Bool) {
        collectionView.reloadData()
        NSUserDefaults.standardUserDefaults().setObject(u, forKey: "u")
        NSUserDefaults.standardUserDefaults().setObject(i, forKey: "i")
        NSUserDefaults.standardUserDefaults().synchronize()

        uV = NSUserDefaults.standardUserDefaults().arrayForKey("u") as! NSArray
        iV = NSUserDefaults.standardUserDefaults().arrayForKey("i") as! NSArray
        print("uV values.. \(uV)")
        print("iV values.. \(iV)")
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return uV.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> FavoriteTvCollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FavoriteTvCollectionViewCell

        cell.imageView.image = UIImage(named: iV[indexPath.row] as! String)
        return cell
    }
}







import UIKit
class FavoriteTvCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
}


推荐答案

我检查过您的示例项目,我做了一个很小的改动,现在工作正常。

I had Checked your sample project,I made a small change now it's working fine.

override func viewWillAppear(animated: Bool) {
    collectionView.reloadData()
    //You have check for availablity of favorute item before adding to userdefault
    if u.count > 0 {
        NSUserDefaults.standardUserDefaults().setObject(u, forKey: "u")
        NSUserDefaults.standardUserDefaults().setObject(i, forKey: "i")
        NSUserDefaults.standardUserDefaults().synchronize()
    }


    uV = NSUserDefaults.standardUserDefaults().arrayForKey("u")!
    iV = NSUserDefaults.standardUserDefaults().arrayForKey("i")!
    print("uV values.. \(uV)")
    print("iV values.. \(iV)")
}

在将对象添加到Userdefault之前检查对象的可用性。现在它的工作正常试试让我知道响应。

Check availability of object before adding it to Userdefault.Now its working fine give it a try and let me know the response pls.

编辑:
我已经编辑了你的代码,现在它工作正常,我听到列出了我所做的所有更改。

I have edited your code now it is working fine,I hear by list out all those changes done by me.


  1. LiveCollectionView.swift 中:

声明两个对象和In viewdidload:

Declaring two objects and In viewdidload:

  var MutableArray:NSMutableArray!
  let defaults = NSUserDefaults.standardUserDefaults()


  override func viewDidLoad() {
     super.viewDidLoad()

      MutableArray = NSMutableArray()
      if let HaveUrl = defaults.objectForKey("u"){
         u = HaveUrl.mutableCopy() as! [NSString]
      }
      if let HaveImage = defaults.objectForKey("i"){
         i = HaveImage.mutableCopy() as! [NSString]
      }


     if let CheckAvailability = defaults.objectForKey("Fav_Unfav"){
        MutableArray = CheckAvailability.mutableCopy() as! NSMutableArray
     }else{
     for var Check in image {
        print(Check)
        MutableArray.addObject("wHeart")
     }
  }
}

cellForItemAtIndexPath:

cellForItemAtIndexPath:

//Add this New Line
cell.heartBt.setImage(UIImage(named: MutableArray[indexPath.row] as! String), forState: UIControlState.Normal)


  • LiveCollectionViewCell.swift:

     class LiveCollectionViewCell: UICollectionViewCell{
    
     var showPlayButton = true
    
     var number = Int()
     var secondNumber = Int()
    
     @IBOutlet weak var playBt: UIButton!
    
     @IBOutlet weak var imageView: UIImageView!
    
     @IBOutlet weak var heartBt: UIButton!
    
     @IBAction func heartBt(sender: UIButton) {
    
    
    var btn : NSInteger
    btn = sender.tag as NSInteger
    
    let uValues = url[btn]
    let iValues = image[btn]
    
    if MutableArray[btn] as! String == "rheart" {
        showPlayButton = false
    }
    
    if showPlayButton == true{
        //Add this Line
        MutableArray.replaceObjectAtIndex(btn, withObject: "rheart")
    
        u.append(url[btn])
        i.append(image[btn])
        self.heartBt.setImage(UIImage(named: "rheart"), forState: UIControlState.Normal)
        showPlayButton = false
        print("rHeart xxxxxxxxxxxxxxx")
    
    }else{
        //Add this Line
        MutableArray.replaceObjectAtIndex(btn, withObject: "wHeart")
    
        for check in u {
    
            number++
            print(number)
    
            if uValues == check{
                print(u)
                u.removeAtIndex(number-1)
                number = 0
                print("RemoVe at indext path")
                print(u)
    
                break
    
            }
    
        }
    
        for check2 in i{
    
            secondNumber++
            print(secondNumber)
    
            if iValues == check2{
                print(i)
                i.removeAtIndex(secondNumber-1)
                secondNumber = 0
                print("RemoVe at indext path")
                print(i)
                self.heartBt.setImage(UIImage(named: "wHeart"), forState: UIControlState.Normal)
                showPlayButton = true
                print("wHeart ........")
                break
    
            }
    
        }
    
    }
       //Set the array to userdefault
        defaults.setObject(MutableArray, forKey: "Fav_Unfav")
        defaults.setObject(u, forKey: "u")
        defaults.setObject(i, forKey: "i")
    
        defaults.synchronize()
       }
    }
    


  • FavoriteTvViewController.swift:

    override func viewWillAppear(animated: Bool) {
       collectionView.reloadData()
    
       if let CheckURL = defaults.objectForKey("u") {
         uV = CheckURL.mutableCopy() as! NSArray
       }
    
       if let CheckImage = defaults.objectForKey("i"){
         iV = CheckImage.mutableCopy() as! NSArray
       }
    
       print("uV values.. \(uV)")
       print("iV values.. \(iV)")
    }
    


  • 这篇关于尝试创建收藏夹按钮以添加收藏列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!