![](/img/trans.png)
[英]How to write the below Android(A-Java) code in the same way of iOS(Objective-C)
[英]Is there any way to write concise code for below case
我有一個帶有兩個標簽的應用程序。 在第一個BookVC
選項卡中,我使用UICollectionViewController
來顯示書籍,在didSelectItemAtIndexPath
我調用了一個推入BookDetailVC
的函數。
在“書簽”選項卡中,我想顯示所有已添加書簽的書,當用戶選擇某些書時,我想按BookDetailVC
。 我知道可以通過編寫與BookVC
相同的代碼來實現。 但是我不想重復相同的代碼。
我會努力讓BookmarkVC
的子類BookVC
並最終成為兩者均顯示同一本書BookVC
和BookmarkVC
因為我使用UICollectionView同一個實例從BookVC
。 有什么方法可以覆蓋UICollectionView
的BookVC
或任何其他方法來解決。 對不起,我的英語不好。 謝謝。
您使用了錯誤的方法。 在您描述書簽和書籍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.