所以我的rootViewController包含一个带有自定义UICollectionViewCell的UICollectionView。我在单元格上有一个标签,标题不应该改变,我有一个多行标签构成单元格其余部分的主体。当我启动应用程序时,它正确调用sizeToFit,顶部对齐所有内容,使其不居中。我单击其中一个单元格并转到下一个视图,然后如果单击后退按钮返回到rootViewController,它会运行viewWillAppear方法并重新加载数据,但sizeToFit不起作用,并且多行上的所有内容标签变为中心对齐。它仍然是多行,但如果只有几行,它就位于标签的中心,看起来不太好。我怎样才能保持这一点以便它是一致的。我有一个左侧菜单,将重新加载rootViewController,它将再次正确定位标签但是一旦我从secondViewController点击后退按钮,它就不再对齐了。有没有办法清除所有单元格并重新加载它们。我试过[collectionView reloadData];在viewWillAppear中它不起作用,它当前在connectionDidFinish的末尾调用,从viewWillAppear方法调用网络连接。任何帮助表示赞赏。
这是自定义UICollectionViewCell代码
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
[contentLabel setNumberOfLines:0];
[contentLabel sizeToFit];
}
RootViewController的
-(UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:
(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"LocationListCell";
LocationList *cell = [cv dequeueReusableCellWithReuseIdentifier:cellIdentifier
forIndexPath:indexPath];
[cell.titleBar setText:[value objectAtIndex:indexPath.row]];
NSArray *tempObject = [[NSArray alloc] initWithArray:[self getData:[key
objectAtIndex:indexPath.row]]];
NSMutableString *tempString = [[NSMutableString alloc] init];
for (int i = 0; i < [tempObject count]; i++)
{
[tempString appendString:[tempObject objectAtIndex:i]];
[tempString appendString:@"\r"];
}
//[cell.contentLabel sizeToFit];
//[cell.contentLabel setNumberOfLines:0];
[cell.contentLabel setText:tempString];
return cell;
}
答案 0 :(得分:1)
将此动态UILable
与此自定义方法一起使用...
只需在.m
文件中添加此方法
-(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
{
[text retain];
[withFont retain];
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
[text release];
[withFont release];
return suggestedSize.height;
}
并像下面那样使用它。
UILabel *yourLable = [[UILabel alloc]init];
[yourLable setFrame:CGRectMake(110, 31, 200, 50)];
[yourLable setText:tempString];
yourLable.lineBreakMode = UILineBreakModeWordWrap;
yourLable.numberOfLines = 0;
yourLable.font = [UIFont fontWithName:@"Helvetica" size:12];
yourLable.frame = CGRectMake(yourLable.frame.origin.x, yourLable.frame.origin.y,
200,[self calculateHeightOfTextFromWidth:yourLable.text :yourLable.font :200 :UILineBreakModeWordWrap] );
yourLable.textColor = [UIColor darkGrayColor];
cell.contentLabel = yourLable;
希望这能帮到你......
答案 1 :(得分:0)
尝试以下几行:
contentLabel.textAlignment = UITextAlignmentLeft;
contentLabel.lineBreakMode = UILineBreakModeWordWrap;
答案 2 :(得分:0)
尝试这样并在.h文件中声明标签
contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 49, 202, 237)];
[contentLabel setNumberOfLines:0];
[contentLabel sizeToFit];
[cell.contentLabel setText:tempString];