大家好,现在有一难题请高手帮忙,用一个动态数组存储用户的照片。
arryData = [[NSArray alloc] initWithObjects:@"pic1.png", @"pic2.png", @"pic3.png", @"pic4.png", @"pic5.png", @"pic6.png",@"pic7.png", @"pic8.png",nil];
数组中包含的照片数量不限,8,20或者100都可以。在tableView中,每行创建4个UIimageView,添加到cell.conentView中。所以要求是:
以此类推
所以问题就是怎么实现这样的数学问题?
- (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
}
还是看一下图片预览效果吧
基本上,你需要除以4,四舍五入,由于在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)/每行显示的条数 + 1
如你有 10个对象,那么需要的行数为
(10-1)/4 + 1 = 3
如你有 5个对象,那么需要的行数为
(5-1)/4 + 1 = 2