Ios SizeToFit未按预期工作
我有一个UITableView,其中包含具有以下实现的单元格:Ios SizeToFit未按预期工作,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我有一个UITableView,其中包含具有以下实现的单元格: static NSString *AttractionCellIdentifier = @"AttractionCell"; AttractionCellTableViewCell *cell = (AttractionCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:AttractionCellIdentifier]; if
static NSString *AttractionCellIdentifier = @"AttractionCell";
AttractionCellTableViewCell *cell = (AttractionCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:AttractionCellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AttractionCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = cell.gradientView.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor]CGColor], nil];
[cell.gradientView.layer insertSublayer:gradient atIndex:0];
cell.gradientView.alpha = 0.8;
}
cell.backgroundPhoto.image = [UIImage imageWithData:photosArray[indexPath.row]];
cell.backgroundPhoto.contentMode = UIViewContentModeScaleAspectFill;
[cell.backgroundPhoto setClipsToBounds:YES];
NSDictionary *morning = [[NSDictionary alloc]initWithDictionary:random[indexPath.row]];
cell.attractionName.numberOfLines = 2;
cell.attractionName.text = [NSString stringWithFormat:@"%@",morning[@"name"]];
[cell.attractionName sizeToFit];
CGRect attractionNameRect = [cell.attractionName frame];
attractionNameRect.origin.x = (self.view.frame.size.width/2) - (attractionNameRect.size.width/2);
[cell.attractionName setFrame:attractionNameRect];
[cell.attractionName setNeedsLayout];
cell.borderView.layer.borderWidth = 2.5f;
cell.borderView.layer.borderColor = [UIColor whiteColor].CGColor;
CGRect borderViewRect = [cell.borderView frame];
borderViewRect.size.width = cell.attractionName.frame.size.width+20;
borderViewRect.size.height = cell.attractionName.frame.size.height+20;
[cell.borderView setFrame:borderViewRect];
borderViewRect.origin.x = cell.attractionName.frame.origin.x-10;
borderViewRect.origin.y = cell.attractionName.frame.origin.y-10;
[cell.borderView setFrame:borderViewRect];
[cell.borderView setNeedsLayout];
这将处理以下屏幕截图中以白色文本显示的attractionName标签,以及borderView,即attractionName标签周围显示的白色边框
重新加载该表时,如下所示:
当我第一次向下滚动时,第一个问题出现在第三个单元格中:
由于某些原因,第三个单元格在第一次滚动时从不更新borderView,并显示带有.xib文件中视图原始尺寸的边框。当我上下滚动到第三个单元格时,borderView才会正确显示
第二个问题发生在我上下滚动表格几次时,隐藏并显示第一个单元格:
最后:
attractionName的宽度逐渐减小,名称被截断,我还不能真正理解为什么。在使用sizeToFit之前,我尝试将每个标签的宽度设置为原始宽度,但这会导致sizeToFit对标签的尺寸没有影响。如果有人能提出一个解决方案,那就太好了:尝试将numberOfLines属性设置为0。这似乎对任何事情都没有影响,因此标签仍然会每次都变窄。更可能的问题是表视图的回收,如果您创建了自己的子类,请尝试在-prepareForReuse中重置所有属性