如何使用按钮更改NSCollectionView的数据

时间:2016-11-02 21:54:11

标签: swift xcode macos swift3 nscollectionview

我有通过JSON进入的数据,我能够根据一些逻辑在我的集合视图中切换数据。如果我登录它会显示一组数据,如果我注销它会显示另一组数据。但现在我想根据按钮推送更改我的集合视图的数据。我有两个按钮。一个显示“所有产品”,另一个显示“已安装的产品”如何合并按钮以在我的数据之间切换?

CollectionView Logic

extension ViewController: NSCollectionViewDataSource, NSCollectionViewDelegate, NSCollectionViewDelegateFlowLayout{


func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {

    let prefs:UserDefaults = UserDefaults.standard
    let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

    if (isLoggedIn == 1) {


    return installedArray?.count ?? 0
    }

    return productsArray?.count ?? 0
}


func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {

    let prefs:UserDefaults = UserDefaults.standard
    let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

    if (isLoggedIn == 1) {


    let item = collectionView.makeItem(withIdentifier: "Installed", for: indexPath) as! Installed

        item.buildProduct = installedArray?[indexPath.item]

    return item
    }

    let itemB = collectionView.makeItem(withIdentifier: "test1", for: indexPath) as! test1

    itemB.buildProduct = productsArray?[indexPath.item]

    return itemB

}

按钮

@IBAction func allAppsPushed(_ sender: Any) {

    let prefs:UserDefaults = UserDefaults.standard
    let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

    if (isLoggedIn == 1) {




    }else{


    }


}

@IBAction func installedPushed(_ sender: Any) {

    let prefs:UserDefaults = UserDefaults.standard
    let isLoggedIn:Int = prefs.integer(forKey: "ISLOGGEDIN") as Int

    if (isLoggedIn == 1) {



    }else{



    }
}

2 个答案:

答案 0 :(得分:0)

尝试在按钮方法中调用collectionView.reloadData()。这将导致collectionView完全重新加载它的数据,并且由于您的isLoggedIn标志已更改状态,您应该加载不同的数据。

答案 1 :(得分:0)

我将我的isLoggedIn移到了我的类之外,使其成为一个全局变量,在每个按钮中我首先设置变量,然后检查我的逻辑,现在它在我的数据之间切换!

@IBAction func allAppsPushed(_ sender: Any) {

    isLoggedIn = 1

    if (isLoggedIn == 1) {

        colView.reloadData()

    }else{

    }
}


@IBAction func installedPushed(_ sender: Any) {

    isLoggedIn = 0

    if (isLoggedIn == 1) {

        colView.reloadData()

    }else{

        colView.reloadData()

    }
}