2014-02-25 41 views
-1

我有一个tableview,我想在单元格中显示多行文本。我尝试了下面的代码和高度变化,但文本不会中断,并且第二行不会出现。你有什么线索我做错了什么?在一个tableview单元格中显示多行

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] 
       initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    } 

    NSString *myString = [_menuItems objectAtIndex:[indexPath row]]; 
    UILabel *settingsLabel = (UILabel *)[cell viewWithTag:201]; 
    settingsLabel.text = myString; 
    settingsLabel.lineBreakMode = NSLineBreakByWordWrapping; 
    settingsLabel.numberOfLines = 0; 
    [settingsLabel sizeToFit]; 

    return cell; 
} 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *str = [_menuItems objectAtIndex:indexPath.row]; 
    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17] constrainedToSize:CGSizeMake(200, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; 
    NSLog(@"%f",size.height); 
    return size.height + 10; 
} 
+0

你在使用故事板吗?什么是你看到上述代码的奇怪行为的iOS版本?我已经使用iOS 7中的故事板进行了轻微修改,尝试了您的代码,它看起来很不错,有两行文字。 – Ricky

+0

是的,我正在使用iOS 7故事板并在iPhone 5(4英寸屏幕)上进行模拟。在我的项目中,我只看到1行文字。也许是与故事板上的标签...... – nabrugir

回答

0

对于快速调试,请设置一些视图的背景颜色,以便您可以确切地看到它们的位置。例如,标签有多大?

而不是使用sizeToFit,看看使用sizeThatFits:与被限制为可用宽度的细胞,并用大高度(你所期望的最大合理的高度)的尺寸。然后,使用该尺寸设置标签框。

更好的是,使用自动布局或自动调整大小来指定标签应该随着单元格增长(其高度)。然后,因为您已经在heightForRowAtIndexPath:中设置了合适的高度,标签应自动调整大小以适应整个文本。

+0

该文本只有1或2行。标签是200x30。 sizeThatFits不起作用。使用自动布局或自动调整大小意味着什么? – nabrugir

+0

https://developer.apple.com/library/ios/documentation/userexperience/conceptual/AutolayoutPG/Introduction/Introduction.html/https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class /UIView/UIView.html#//apple_ref/occ/instp/UIView/autoresizingMask – Wain

相关问题