2015-11-07 18 views
-1

我有任何数量的单个数组。我想在不同的部分划分为7的倍数。我无法得到这个工作。这是一个2个元素的例子。如何在节中操作数组?

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    array =[NSMutableArray arrayWithObjects:@"d",@"s",@"a",@"qq",@"dqd",@"dqq",@"qdqdf",@"dqdfqf", nil]; 

    // Do any additional setup after loading the view from its nib. 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return ceil(array.count/2.0); // round up the floating point division 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSInteger sections = [self numberOfSectionsInTableView:tableView]; 
    if (section == sections - 1) { 
     NSInteger count = array.count & 2; 
     if (count == 0) { 
      count = 2; 
     } 
     return count; 
    } else { 
     return 2; 
    } 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *simpleTableIdentifier = @"SimpleTableItem"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 
    } 

    // cell.textLabel.text = [tableData objectAtIndex:indexPath.row]; 
    return cell; 
} 
+0

@rmaddy请帮助这项工作 –

+1

发布答案后不要完全改变你的问题。它使答案毫无价值。 – rmaddy

回答

2

你的问题还不清楚,但我想你想在除了最后一节每节7行这将对刚好够不适合的部分,其余剩下的最后行。

假设这是正确的,你需要正确计算部分的数量如下:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return ceil(array.count/7.0); // round up the floating point division 
} 

现在,在每个部分的行数将是7除了最后一节可能有1 - 7。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSInteger sections = [self numberOfSectionsInTableView:tableView]; 
    if (section == sections - 1) { 
     NSInteger count = array.count % 7; 
     if (count == 0) { 
      count = 7; 
     } 
     return count; 
    } else { 
     return 7; 
    } 
} 

您还需要能够到indexPath转换成数组索引:

NSInteger index = indexPath.section * 7 + indexPath.row; 

而且你需要能够到数组索引转换成indexPath:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index % 7 inSection:index/7]; 

,而不是所有这一切或者,你可以设置你的数据结构是数组的数组。这实际上使您的数据更好地匹配表格的使用方式。

更新您修订问题:

cellForRowAtIndexPath方法需要改变:

//cell.textLabel.text = [tableData objectAtIndex:indexPath.row]; 

到:

NSInteger index = indexPath.section * 7 + indexPath.row; 
cell.textLabel.text = tableData[index]; 

就像我上面显示。

+1

我已经告诉过你在'tableView:numberOfRowsInSection:'方法后显示给你的代码行中。 – rmaddy

+1

顺便说一句 - 有一个错字。将'array.count&7'改为'array.count%7'。 – rmaddy

+0

所有部分前两个元素填充在所有部分中。 –

1

所以我并不完全在于Objective-C的观点,因为它已经有一段时间了。

但我认为要做的最简单的事情就是循环遍历整个数组的长度,并且每隔7位将分割数组。

这是一些伪码。

for(int i =0; i<array.length<i=i+7) 
{ 
    //take the first index, take the 7th index. 
    //split the array from the first index to the 7th 
    //repeat for all remaining values. 
} 

我不知道你是否想要所有不同的部分,它可以从7间隔,或只有一个。如果你能澄清我可以更好地回答这个问题。