2017-08-03 157 views
0

我有一個應用程序,它有兩個選項卡。在第一個BookVC選項卡中,我使用UICollectionViewController來顯示書籍,並在didSelectItemAtIndexPath中調用了一個推送BookDetailVC的函數。有沒有什麼辦法可以編寫簡潔的代碼?

而在書籤標籤中,我想顯示所有已書籤的書籍,當用戶選擇某本書時,我想推BookDetailVC。我知道這可以通過編寫與BookVC相同的代碼來實現。但我不想重複相同的代碼。

我試圖讓BookmarkVC子類的BookVC,並最終成爲展示,因爲我使用UICollectionView同一個實例從BookVC兩個BookVCBookmarkVC同一本書。有什麼方法可以覆蓋的BookVC或其他任何解決方法。對不起,我的英語不好。謝謝。

enter image description here

回答

0

你採取錯誤的做法。您描述書籤和書籍視圖控制器的方式,在我看來,它們是相同的,唯一改變的是內容。

因此,由於集合視圖使用數據源,所以您只需根據是要顯示所有書籍還是隻顯示書籤來更改數據源。


添加代碼:

let storyboard = UIStoryboard(name: "Main", bundle: nil) 
let viewController = storyboard.instantiateViewController(withIdentifier :"secondViewController") as! UIViewController 
self.present(viewController, animated: true) 
+0

是的,他們是相同的創建CollectionViewDelegate方法。但我想單獨顯示他們的VC。所以我嘗試從bookvc繼承bookmarkvc,併爲數據源過濾只有書籤的對象。 – noob

+0

你不需要子類,這取決於你如何聲明你的接口,例如,如果你用這個BooksVC創建一個新的故事板,那麼你可以通過編程方式實例化它並隨時顯示它,並在代碼中使用標誌或某物來設置代表。請參閱附件中的代碼。 – Pochi

+0

@noob它不是很好,爲相同的數據分離vc,我已經發布解決方案創建模型的書,你可以很容易地識別哪本書是bookMarked –

0

我認爲你做錯了使用只需要在此基礎上按鈕被點擊重新加載集合視圖採取布爾 isBookMarkCliked:BOOL

爲更好可讀性創建模型書 像

class Book { 
    var title: String 
    var author: String 
    var isBookMarked:Bool 
    init(title: String, author: String, isBookMarked:Bool) { 
     self.title = title 
     self.author = author 
     self.isBookMarked = isBookMarked 
    } 
} 

,並聲明兩個陣列與全球Book模型

arrForBooks:[Book] = [] 
arrForBookMarkedBooks:[Book] = [] 

使用延長

extension YourClassVC: UICollectionViewDataSource,UICollectionViewDelegate 
{ 

    //MARK: UICollectionViewDataSource 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    { 
     if isBookMarkClicked 
     { 
     return arrForBookMarkedBooks.count 
     } 
     return arrForBooks.count 
    } 

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

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellIdentifier", for: indexPath) as! YourCellClass 
     var currentBook:Book = nil 
     if isBookMarkClicked 
      currentBook = arrForStoreDetails[indexPath.row] 
     else 
      currentBook = arrForBookMarkedBooks[indexPath.row] 

     //Set data to cell from currentBook 
     return cell 

    } 

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

     collectionView.deselectItem(at: indexPath, animated: false) 
     //Your code to push BookDetailVC 
    } 

} 
相關問題