开发者

UITableView to display keyvalue pairs

开发者 https://www.devze.com 2023-03-31 23:23 出处:网络
I have a list of name and values I need to display. It\'s difficult to maintain lots of labels and associa开发者_开发知识库ted content textfields in IB so I\'m thinking of usingUITableView. Is there a

I have a list of name and values I need to display. It's difficult to maintain lots of labels and associa开发者_开发知识库ted content textfields in IB so I'm thinking of using UITableView. Is there a way to fix the labels for cells, then just either bind to an NSDictionary and display the key/value names or fix the cells and labels in a UITableView?


You can't bind to the table view as you might do when writing OS/X apps, but the two methods below, in your UITableView's datasource should do the trick:

@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;
}

or in Swift

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
}


Just read this Table View Programming Guide for iOS and everything will be clear for you.

You can use next table view cell's types : UITableViewCellStyleValue1 or UITableViewCellStyleValue2. They have two labels as you need (one for key and one for value).

Or you can create your own cell style and set values for labels using there tags.

0

精彩评论

暂无评论...
验证码 换一张
取 消