2011-08-30 78 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