2015-11-07 62 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間隔,或只有一個。如果你能澄清我可以更好地回答這個問題。