簡體   English   中英

uitableview numberOfRowsInSection計數

[英]uitableview numberOfRowsInSection count

這比任何其他問題都更是一個數學問題。 我所擁有的是一個動態數組對象,用於存儲用戶照片。

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

該數組可以包含任意數量的對象,例如8或20或100。在我的表視圖中,通過將它們添加到cell.contentview中,每行創建了4個UIImageViews。 所以如果說

  • 如果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

    }

圖片值一千字。

在此處輸入圖片說明

因此,基本上,您需要除以四,然后四舍五入。 由於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;
}

對於行數,除以圖像數並四舍五入:

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

我想您只有一節,所以:

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

我不得不為我不久前寫的一個應用程序創建類似的東西(似乎您想在每個單元格中包含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;

    }`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM