2016-11-02 10 views
0

JSONを介してデータが入力されていて、ロジックに基づいてコレクションビューのデータを切り替えることができました。私がログインしている場合は、1組のデータが表示され、ログアウトした場合は別のデータが表示されます。しかし、今私はボタンプッシュに基づいて私のコレクションビューのデータを変更したい。私は2つのボタンを持っています。 1つは「すべての製品」を示し、もう1つは「インストールされた製品」を示します。どのようにしてボタンのプッシュを組み込んでデータを切り替えることができますか?ボタンを使用してNSCollectionViewのデータを変更する方法

CollectionViewロジック

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{ 



    } 
} 

答えて

0

ボタンは、ボタンの方法でcollectionView.reloadData()を呼び出してみてください。これにより、collectionViewはデータを完全にリロードし、isLoggedInフラグが状態を変更したため、異なるデータをロードする必要があります。

+0

あなたの言っていることを理解していますが、ログインしていてもデータが変わるだけです。私がログインしているかどうかに頼るのは嫌です。私は純粋にボタンのプッシュに基づいて変更する必要があります。私はあなたが言ったことを試みたが、何も変わらなかった。既に存在している同じデータをリロードして切り替えません。 – Eseye

+0

ボタンでビューコントローラのインスタンス変数を変更し、コレクションビューの 'collectionView:cellForItemAtIndexPath:'メソッドでそのインスタンス変数の値を使用して、コレクションビューに表示するものを決定します。 –

+0

このようなものの例がありますか?私は働いている解決策がありますが、あなたの方法についても興味があります。 – Eseye

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

    } 
} 
関連する問題