2011-08-30 79 views
1

我有我需要顯示的名稱和值的列表。在IB中維護大量標籤和關聯的內容文本域是很困難的,所以我正在考慮使用UITableView。有沒有辦法修復單元格的標籤,然後只是綁定到一個NSDictionary並顯示鍵/值的名稱或修復UITableView中的單元格和標籤?UITableView顯示鍵值對

+0

你有每個細胞有多少項目?如果您沒有太多(通過使用多行等),您可以輕鬆使用現有的單元功能 – TommyG

回答

3

不能綁定到表視圖,你可能會寫OS/X應用程序的時候做的,但下面的兩種方法,在你的UITableView的數據源應該做的伎倆:

@property (strong, nonatomic) NSDictionary * dict; 
@property (strong, nonatomic) NSArray * sortedKeys; 

- (void) setDict: (NSDictionary *) dict 
{ 
    _dict = dict; 
    self.sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)]; 

    [self.tableView reloadData]; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [self.sortedKeys count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath]; 

    NSString * key = self.sortedKeys[indexPath.row]; 
    NSString * value = dict[key]; 

    cell.textLabel.text = key; 
    cell.detailTextLabel.text = value; 

    return cell; 
} 

或在斯威夫特

var sortedKeys: Array<String> = [] 
var dict:Dictionary<String, String> = [:] { 
didSet { 
    sortedKeys = sort(Array(dict.keys)) {$0.lowercaseString < $1.lowercaseString} 
    tableView.reloadData() 
} 
} 

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { 
    return sortedKeys.count 
} 

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { 

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell 

    let key = sortedKeys[indexPath.row] as String 
    let value = dict[key] as String 

    cell.textLabel.text = key 
    cell.detailTextLabel.text = value 

    return cell 
} 
+0

謝謝,這是一個非常有用的答案。 – Echilon

+0

在每次調用cellforrow時,對字典進行一次排序(即設置時)而不是排序它會更好嗎? –

+0

絕對 - 更新了代碼示例以顯示 –

1

剛剛閱讀這個Table View Programming Guide for iOS,一切都將爲你清楚。

您可以使用下一個表格視圖單元格的類型:UITableViewCellStyleValue1UITableViewCellStyleValue2。根據需要,它們有兩個標籤(一個用於鍵和一個用於值)。

或者您可以創建自己的單元格樣式並使用標籤爲標籤設置值。

+0

謝謝。作爲參考,對於'UITableViewCellStyleValue1',標籤是'UITableViewCellStyleValue2'上最寬的部分,關鍵是最廣泛的部分(最好如果你有短名稱的長值)。 – Echilon