2013-11-26 16 views
5

通常我將數據存儲在一個數組中。然後,當調用cellForRowAtIndexPath時,我只需查看行並根據行和進程選擇數組上的項。在分組模式下,UITableView的數據結構如何?

但是我們知道UITableView可以做組視圖。

那我該怎麼辦?我有一個數組的數組?一個數組的NSDictionary?在UITableView結構中存儲數據的最優雅方式是什麼?

回答

10

例如字典的陣列,其中每個字典保持 標題和一個區段上的所有項目:

NSArray *dataSource = @[ 
        @{@"title": @"Section 0", 
         @"rows" : @[ item00, item01, item02] }, 
        @{@"title": @"Section 1", 
         @"rows" : @[ item10, item11, item12] }, 
        @{@"title": @"Section 2", 
         @"rows" : @[ item20, item21, item22] }, 
        ]; 

的項目可以是自定義類的串或對象。然後,您可以 訪問每個項目cellForRowAtIndexPath

Item *item = dataSource[indexPath.section][@"rows"][indexPath.row]; 

和所有其他數據源的方法也很容易實現。

+0

太棒了。這也是我的想法。 –

+0

這是一個很好的方法。它有助於保持所有與UITableView相關的代碼的清潔和易於管理。 – dustinrwh

0

@Martin的答案對於Objective-C是正確的,但在Swift中,我們沒有奢侈的字典變量types。類型是預定義的。

我們需要使用struct或自定義數據類型來解決。

struct Model<Item>{ 
    let title: String 
    let rows: [Item] 

    subscript(index: String) -> [Item] { 
    get { 
     return rows 
    } 
    } 
} 

let model1 = Model(title: "Secton 0", rows: ["A", "B", "C"]) 
let model2 = Model(title: "Secton 1", rows: ["D", "E", "F"]) 

let dataSource = [model1, model2] 

// You can query 
dataSource[indexPath.section][rows][indexPath.row]