如何将动态行和节数组传递给numberOfRowsInSection和cellForRowAtIndexPath

时间:2018-02-09 12:18:57

标签: ios objective-c arrays iphone uitableview

我很多天都面临着这个问题。任何人都可以解决这个问题。

下面是我的行数组,哪个计数应该传入numberOfRowsInSection

    (
        (
        "Service Speed",
        "Good Service",
        "Confirmation quality",
        "Quick Service in Reservation"
    ),
        (
        "Check In",
        "Happy on their Service",
        Courtesey,
        "Quick Service at Checkin"
    ),
        (
        "Front office & reception",
        "Overall Quality of Room",
        Check,
        "Response time"
    ),
        (
        "Room Decor",
        "Time taken to serveTime taken to serveTime taken t",
        Bathroom,
        "Facilities in the Room",
        "Choice of menu",
        Housekeeping,
        "Room Service"
    ),
        (
        "Overall Comments",
        "Will you come back again"
    ),
    "Guest Satisfaction Ratings"
  )

我的问题是,如何传递numberOfRowsInSection中的行数组计数和cellForRowAtIndexPath中的数组值?

我尝试使用下面的代码,但我收到错误:

  

“[__ NSCFString count]:无法识别的选择器发送到实例”

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [GroupName count];
}


-(UITableViewCell *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [GroupName objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[RowsArr objectAtIndex:section] count];
}


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

  cell.Label.text = [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

}

问题出在数组的最后一个对象中 “客人满意度评分”,  因为它来自NSString所以只显示错误。

2 个答案:

答案 0 :(得分:0)

你的问题在这里

[[RowsArr objectAtIndex:section] count];

[RowsArr objectAtIndex:section]返回的字符串不是数组,因此count不能应用于字符串

另外,您发送了RowsArr的点数,并sections

访问了cellForRow arr

答案 1 :(得分:0)

Sh_Khan走在正确的轨道上。你的问题在于:

[[RowsArr objectAtIndex:section] count];

您需要确定所获取对象的类型,例如:

if ([[RowsArr objectAtIndex:section] isKindOfClass:[NSArray class]]) {
    return [[RowsArray objectAtIndex:section] count];
} else {
    return 1;
}

一旦你这样做,你也会遇到

的问题
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

因为这也假设你会得到一个数组。

更改行:

cell.Label.text = [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

有:

cell.Label.text = [[sections objectAtIndex:indexPath.section] isKindOfClass:[NSArray class]] 
    ? [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] 
    : [sections objectAtIndex:indexPath.section];

并且它将处理这两种情况。

编辑:不确定您从哪里获得sections,因此您可能需要将最后一个更改为:

cell.Label.text = [[RowsArr objectAtIndex:indexPath.section] isKindOfClass:[NSArray class]] 
    ? [[RowsArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] 
    : [RowsArr objectAtIndex:indexPath.section];