2016-12-28 55 views
0

我有UICollectionView和選定的單元格應該喜歡圖片中的黃色。那麼如何爲選中的單元格設計一個單獨的設計,以及如何在其上繪製曲線? 我應該爲此使用2個單獨的UICollectionViewCell嗎?或者有任何替代方法可以在選擇時重用相同的單元格。UICollectionView與2個獨立的設計

enter image description here

+0

在單個單元格中創建這2個視圖。然後,用didSelectItemAtIndex檢測單元格選擇並更改該特定單元格的視圖類型。 – SNarula

+1

您可以更改所選單元格的背景圖像,爲所選單元格取景並取消選擇,每當用戶選擇該單元格時,只需選擇背景圖像即可 – Diksha

回答

1

要不要我用2個獨立的UICollectionViewCell這個?

這是一條路。如果有更多的差異,而不僅僅是你所描述的那樣,那麼做。

或者有任何替代方法可以在選擇時重用相同的單元格。

當然,你可以這樣做。看看插圖中的兩個單元格,但將每個單元格上面的灰色部分視爲單元格的一部分。黑色矩形和黃色凸起的矩形只是您在單元格背景中繪製的兩幅不同的圖像,您只需通過更改該圖像即可配置相同類型的單元格。如果單元的其他方面(如標籤位置等)在兩個單元之間相同,則這是一種很好的方法。

1

如果這是您想在選擇之後做出的唯一不同之處,我認爲沒有必要創建兩個不同的UICollectionViewCell s,而需要保留所選單元格的indexpath.row(s) s)並檢查這是否是選定的行,更改/添加新的背景圖像。

例如:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 
    // here is the variable that should save the current selected row... 
    private var selectedRow: Int? 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return 10 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     // let's consider that you have a custom cell called "MyCustomCell" 
     // which has "backgroundImage" property... 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyCustomCell 

     // checking based on the selected row 
     cell.backgroundImage = indexPath.row == selectedRow ? UIImage("yellow") : UIImage("default") 

     return cell 
    } 

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     selectedRow = indexPath.row 
     collectionView.reloadData() 
    } 
} 

需要注意的是,如果你想檢查多行,你應該聲明selectedRows爲int數組(或可能爲一組)。

希望它有幫助。