簡體   English   中英

有什么辦法可以在下面的情況下編寫簡潔的代碼

[英]Is there any way to write concise code for below case

我有一個帶有兩個標簽的應用程序。 在第一個BookVC選項卡中,我使用UICollectionViewController來顯示書籍,在didSelectItemAtIndexPath我調用了一個推入BookDetailVC的函數。

在“書簽”選項卡中,我想顯示所有已添加書簽的書,當用戶選擇某些書時,我想按BookDetailVC 我知道可以通過編寫與BookVC相同的代碼來實現。 但是我不想重復相同的代碼。

我會努力讓BookmarkVC的子類BookVC並最終成為兩者均顯示同一本書BookVCBookmarkVC因為我使用UICollectionView同一個實例從BookVC 有什么方法可以覆蓋UICollectionViewBookVC或任何其他方法來解決。 對不起,我的英語不好。 謝謝。

在此處輸入圖片說明

您使用了錯誤的方法。 在您描述書簽和書籍View控制器的方式上,在我看來它們是相同的,唯一改變的是內容。

因此,由於館藏視圖使用數據源,所以您要做的就是根據要顯示所有書籍還是僅顯示加書簽的書籍來更改數據源。


添加的代碼:

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

我認為您使用錯了,只需要根據單擊的按鈕重新加載集合視圖,就可以使用boolean 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 Model全局聲明兩個數組

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

使用擴展創建CollectionViewDelegate方法

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
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM