将表视图中的内容显示为节中的单元格

时间:2014-09-01 03:28:17

标签: objective-c

我有两个数组。一个有学生详细信息,另一个有员工详细信息阵列中的这些细节是通过更改视图控制器中的段来获得的。我想将这些数组作为单元格内容显示在两个部分中。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

这是我认为你正在寻找的一个简单的工作实现:

- (void)viewDidLoad {
    [super viewDidLoad];

    // here is the staff and students array for demonstration purposes
    self.staff = @[@"Mr. Jones", @"Mrs. Smith", @"Principal Alfred", @"Miss Agnes"];
    self.students = @[@"Timmy", @"Joey", @"Suzie"];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // there will be two sections, the staff array in the first section
    // and the student array for the second section
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // if this section is the first section, return the number of cells as there
    // are staff entries in the array, otherwise this is the second section so we
    // can return the number of students in the array
    return section == 0 ? self.staff.count : self.students.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // try to reuse a cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    // if we had no cells to reuse, create one
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    // now we can customize the cell based on the index path. If this is the first section
    // we want to display the staff information, and if this is the second section we want to display
    // the student information, but in both cases we use the row to figure out which entry in each
    // array we want to use. Assuming the arrays are filled with name strings, we can just set the
    // textLabel's text to the name for this section/row
    NSString *name = indexPath.section == 0 ? self.staff[indexPath.row] : self.students[indexPath.row];
    cell.textLabel.text = name;

    // then return the cell
    return cell;
}

@end

enter image description here

如果您不熟悉内联条件,两者完全相同:

// this means return the count of the staff array if the section is 0, otherwise return the
// count of the student array, just like the if-statement below
return section == 0 ? self.staff.count : self.students.count;

// this is the same as the in-line conditional above, and while less concise and compact,
// it is more likely understood in many cases
if (section == 0) {
    return self.staff.count;
}
else {
    return self.students.count;
}
相关问题