2016-08-25 31 views
0

我正在構建一個應用程序,在UITableView中有幾個部分。我目前的解決方案是在字典中收集我的數據,然後爲每個部分選擇一個鍵。有更好的解決方案嗎?在UITableView的部分中填充行的最佳方法是什麼?

+0

1)段號=字典中沒有鍵2)段號中的行數=段號中字典中沒有值的值 – pkc456

+0

確切地說,是這樣做的嗎? – Recusiwe

+0

是的,這是正確的方法。我還應該分享代碼嗎? – pkc456

回答

0

這裏是我寫的一個快速例子。請注意,它很容易出錯,因爲它不檢查密鑰是否存在,也不會創建合適的單元格。

你也可以用字典來做到這一點,因爲你可以迭代它的內容。

希望它能幫助:

class AwesomeTable: UITableViewController { 

    private var tableContent: [[String]] = [["Section 1, row 1", "Section 1, row 2"], ["Section 2, row 1", "Section 2, row 2"]] 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return tableContent.count 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return tableContent[section].count 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) 

     let item = tableContent[indexPath.section][indexPath.row] 

     cell.textLabel?.text = item 

     return cell 
    } 

} 
+0

這不是一個很好的做法。 1)。大規模地維護該詞典的內容是非常困難的。 2)。對大字典進行排序或排序幾乎是不可能的。 3)。 4)創建非常複雜的單元非常困難。如果您的單元格類型超過1個或2個,那麼它會變得亂糟糟,因爲您的cellForRowAtIndexPath 513)。沒有明確設置。你只會傳遞正確的字典內容,這是不好的。 –

+0

我同意,但考慮到它回答它的問題。有很多方法可以更好地做到這一點,其中一個就是你給出的答案。在你的回答中,代碼更清晰,更易於閱讀,但我想爭辯說,複雜性仍然大致相同。 –

2

其中一個很好的辦法吧 - 直銷模式的映射,尤其是與迅速枚舉良好。例如,你有2個不同的部分,3種不同類型的行。您的enum和ViewController代碼如下所示:

enum TableViewSectionTypes { 
    case SectionOne 
    case SectionTwo 
} 

enum TableViewRowTypes { 
    case RawTypeOne 
    case RawTypeTwo 
    case RawTypeThreeWithAssociatedModel(ModelForRowTypeNumberThree) 
} 

struct ModelForRowTypeNumberThree { 
    let paramOne: String 
    let paramTwo: UIImage 
    let paramThree: String 
    let paramFour: NSData 
} 

struct TableViewSection { 
    let type: TableViewSectionTypes 
    let raws: [TableViewRowTypes] 
} 

class ViewController: UIViewController, UITableViewDataSource { 

    var sections = [TableViewSection]() 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return sections[section].raws.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let raw = sections[indexPath.section].raws[indexPath.row] 
     switch raw { 
     case .RawTypeOne: 
      // Here return cell of first type 
     case .RawTypeTwo: 
      // There return cell of second type 
     case .RawTypeThreeWithAssociatedModel(let modelForRawTypeThree): 
      // And finally here you can use your model and bind it to your cell and return it 
     } 
    } 
} 

有什麼好處?強大的典型化,明確的建模和顯式處理您的各種細胞類型。在這種情況下你必須做的唯一簡單的事情就是將你的數據解析成這個枚舉和結構,以及你爲你的字典做的。

+0

這似乎很有希望解決我的問題。不過,我無法弄清楚如何將我的Firebase數據庫中的數據解析到枚舉中。我可以直接將數據從數據庫加載到枚舉中嗎?或者我在哪裏執行此步驟? 我已經有一個像我的ModelForRowTypeNumberThree結構。 在我的應用程序中,所有的行類型都是相同的,但是由4個不同的NSDictionarys填充。這可能嗎? – AlexVilla147

相關問題