2013-06-20 50 views
0

這是一個比其他任何問題更多的數學問題。我擁有的是一個動態數組對象,我在其中存儲用戶照片。uitableview numberOfRowsInSection count

arryData = [[NSArray alloc] initWithObjects:@"pic1.png", @"pic2.png", @"pic3.png", @"pic4.png", @"pic5.png", @"pic6.png",@"pic7.png", @"pic8.png",nil]; 

該陣列可以具有對象的任何量在它e.g 8或20或100。以我的表視圖我已經創建每行4周的UIImageViews通過將其添加到cell.contentview。所以,如果讓我們說

  • 如果arryData有3個對象的話,我想UITable創建1行
  • 如果arryData有4個對象,然後我想UITable創建1行
  • 如果arryData有5個對象,然後我想UITable創建2行
  • 如果arryData有8個目標,然後我想UITable創建2行
  • 如果arryData有10個對象的話,我想UITable創建3行
  • ....等等

那麼如何在我的arryData中爲N個對象執行此操作?

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

     //NSLog(@"Inside numberOfRowsInSection"); 
     //return [arryData count]; 

//Cannot think of a logic to use here? I thought about dividing [arryData count]/4 but that will give me fractions 

    } 

圖片勝過千言萬語。

enter image description here

回答

5

所以基本上你需要除以四,四捨五入。由於在Objective-C截斷(發向零)整數除法,你可以這樣做圓了:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return (arryData.count + 3)/4; 
} 

一般情況下,使整數除法(正整數)圍捕,你加分母-1分割前的分子。

如果您已經爲每行圖像數定義了一個常量,請使用它。例如:

static const int kImagesPerRow = 4; 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return (arryData.count + kImagesPerRow - 1)/kImagesPerRow; 
} 
+1

這真的很不錯:)。 – danypata

+0

哇,謝謝。真正驚訝於你的數學方程! :) –

0

我想你只有一款這樣:通過圖像的數量

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSInteger photoNumber = [yourDataSource count]; 
    if(photoNumber % numberOfPhotosOnRow == 0) { 
     return photoNumber/numberOfPhotosOnRow; 
    } 
    else { 
     return photoNumber/numberOfPhotosOnRow + 1; 
    } 
} 
1

對於行數,分圓了:

rowCount = ceilf([arryData count]/4.0); 
+1

當用'4.0'('double')劃分時,使用'ceilf'('float'函數)沒有意義。除以'4.0f'或使用'ceil'。 –

0

我不得不創建類似的應用程序,我寫了一段時間後(似乎你想包括每個單元格4張圖片)`

if (tableView == yourTableView) 
    { 
     int rows = [yourArray count]; 

     int rowsToReturn = rows/4; 
     int remainder = rows % 4; 
     if (rows == 0) { 
      return 0; 
     } 
     if (rowsToReturn >0) 
     { 
      if (remainder >0) 
      { 
       return rowsToReturn + 1; 
      } 
      return rowsToReturn ; 

     } 
     else 
      return 1; 

    }` 
相關問題