使用字符串数组填充UI表视图

时间:2014-05-05 19:56:49

标签: ios uitableview

我无法在任何地方找到简单,简洁的答案,我拒绝相信XCode会像我在那里找到的其他教程那样努力......

说我有以下数组

NSArray* days = [NSArray arrayWithObjects:@"Sunday",@"Monday",@Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday",nil];

我有一个UI表格视图,table_Days,我想简单地显示我的数组中的项目。填充表格的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

以下是我的完整解释,从与您的情况极为相似的案例开始:

http://www.apeth.com/iOSBook/ch21.html#_table_view_data

因此假设days存储为通过属性self.days访问的实例变量。然后将self设置为表格视图的datasource并使用以下代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (!self.days) // data not ready?
        return 0;
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
        numberOfRowsInSection:(NSInteger)section {
    return [self.days count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:@"Cell"
                                        forIndexPath:indexPath];
    cell.textLabel.text = (self.days)[indexPath.row];
    return cell;
}

答案 1 :(得分:0)

您应该使用data source methods填充表格视图。返回数组的count以获取行数。

如果您需要检测用户何时点按某个单元格,您可以使用delegate方法。

@interface ViewController<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, copy) NSArray *days;
@property (nonatomic, strong) UITableView *tableDays;

@end

@implementation ViewController

-(void)viewDidLoad
{
    [super viewDidLoad];

    UITableView *tableDays; // Set this up
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    tableDays.delegate = self;
    tableDays.dataSource = self;

    [self.view addSubview:tableDays];
    self.tableDays = tableDays;

    self.days = @[@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"];
}

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

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

    cell.textLabel.text = self.days[indexPath.row];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *day = self.days[indexPath.row];
    NSLog(@"Day tapped: %@", day);
}

@end

如果您只想显示表格视图,则应考虑使用UITableViewController

请注意,更好的做法是使用驼峰大小写变量。

相关问题