標籤:
1.在cell初始化的時候建立scrollView,然後往scrollView中添加imageView,最後在重用cell的時候動態計算scrollView的高度
總而言之,就是初始化建立控制項要放在cell的init裡面,賦值放init外面,不然每次迴圈都會重複建立imageView視圖
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cellid"];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellid"];
//滾動視圖
self.scrollView=[[UIScrollView alloc]init];
self.scrollView.tag=9;
//為scrollview建立圖片
CGFloat scrollviewWidth=[UIScreen mainScreen].bounds.size.width-26;
int hang=[self.imagesArray count]%3==0? (int)[self.imagesArray count]/3:(int)[self.imagesArray count]/3+1;
int imgwidth=(scrollviewWidth-10)/3;
for (int i=0; i<hang; i++) {
for (int j=0; j<3; j++) {
if (i*3+j==self.imagesArray.count) {
break;
}
UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(j*(imgwidth+5), i*(imgwidth+5), imgwidth, imgwidth)];
imgView.image=[UIImage imageNamed:[self.imagesArray objectAtIndex:i*3+j]];
[self.scrollView addSubview:imgView];
}
}
[cell.contentView addSubview:self.scrollView];
}
else{
self.scrollView=(UIScrollView *)[cell.contentView viewWithTag:9];
}
//根據文字數量計算UILabelContent高度(已修改)
CGFloat labelWidth=[UIScreen mainScreen].bounds.size.width-26;
NSDictionary *attrs=@{NSFontAttributeName:self.labelContent.font};
CGSize maxSize=CGSizeMake(labelWidth, MAXFLOAT);
CGSize size=[self.labelContent.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
self.labelContent.frame=CGRectMake(13, 89, size.width, size.height);
//scrollview隨著圖片的增多而變高
CGFloat scrollviewWidth=[UIScreen mainScreen].bounds.size.width-26;
int hang=[self.imagesArray count]%3==0? (int)[self.imagesArray count]/3:(int)[self.imagesArray count]/3+1;
int imgwidth=(scrollviewWidth-10)/3;
self.scrollView.backgroundColor=[UIColor lightGrayColor];
self.scrollView.frame=CGRectMake(13, 89+size.height+10, scrollviewWidth, (hang)*imgwidth+(hang-1)*5);
}
ios開發 在cell中動態添加圖片解決重複出現圖層問題