我知道如何在UILabel对齐文本。但这个问题有点复杂。所有其他对齐工作,如NSTextAlignmentJustified、NSTextAlignmentNatural。只有NSTextAlignmentCenter不能使文本处于中心位置。我的UILabel是使用StoryBoard插入的。然后,UILabel的文本格式在程序中实现为
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];
CGRect frame = cell.cellText.frame;
frame.size.width = cell.bounds.size.width;
frame.size.height = cell.bounds.size.height;
cell.cellText.frame = frame;
cell.cellText.font = [UIFont fontWithName:@"ArialMT" size:screenRect.size.height*0.0163];
cell.cellText.textAlignment = NSTextAlignmentCenter;
cell.cellText.lineBreakMode = NSLineBreakByWordWrapping;
cell.cellText.numberOfLines = 0;
cell.cellText.clipsToBounds = YES;
cell.cellText.backgroundColor = [UIColor clearColor];
cell.cellText.textColor = [UIColor blackColor];
if(indexPath.section == 0){
cell.backgroundColor=[UIColor blackColor];
cell.cellText.textColor = [UIColor whiteColor];
if(indexPath.item == 0)
cell.cellText.text = @"Date";
else if(indexPath.item == 1)
cell.cellText.text = @"Age";
else if(indexPath.item == 2)
cell.cellText.text = @"Height (cm)";
else if(indexPath.item == 3)
cell.cellText.text = @"%le";
else if(indexPath.item == 4)
cell.cellText.text = @"Weight (kg)";
else if(indexPath.item == 5)
cell.cellText.text = @"%le";
}
else if(indexPath.section % 2 == 0 && indexPath.section != 0)
cell.backgroundColor=[UIColor grayColor];
else
cell.backgroundColor=[UIColor lightGrayColor];
return cell;
}为什么不能对齐中心,如图中所示。

编辑:我改变了UILabel的背景
if(indexPath.section == 0){
cell.backgroundColor=[UIColor blackColor];
cell.cellText.textColor = [UIColor whiteColor];
cell.cellText.backgroundColor = [UIColor redColor];
if(indexPath.item == 0)
cell.cellText.text = @"Date";
else if(indexPath.item == 1)
cell.cellText.text = @"Age";
else if(indexPath.item == 2)
cell.cellText.text = @"Height (cm)";
else if(indexPath.item == 3)
cell.cellText.text = @"%le";
else if(indexPath.item == 4)
cell.cellText.text = @"Weight (kg)";
else if(indexPath.item == 5)
cell.cellText.text = @"%le";
}更新的图片是

发布于 2015-12-11 10:46:58
不要使用框架来设置cellText的位置。该单元格尚未在collectionView:cellForItemAtIndexPath中放置,因此框架将是错误的。这是完全合理的,框架将是最后一次该细胞被重复使用的框架。
相反,使用AutoLayout将UILabel约束到单元格的所有边缘。
发布于 2015-12-11 10:58:40
替换这些线路
CGRect frame = cell.cellText.frame;
frame.size.width = cell.bounds.size.width;
frame.size.height = cell.bounds.size.height;
cell.cellText.frame = frame;用这个密码。
cell.cellText.center = cell.center;
CGRect frame = cell.cellText.frame;
frame.size.width = cell.bounds.size.width;
frame.size.height = cell.bounds.size.height;
cell.cellText.frame = frame;如果您想使用autolayout,那么只需添加两个约束--两个是您的标签。

https://stackoverflow.com/questions/34220872
复制相似问题