调整UILabel以适应?

如何从iPhone Developer's Cookbook第6章的“09a - PrefsTable”食谱中修改以下片段(在tableView:cellForRowAtIndexPath:UITableViewController方法中):

if (row == 1) { 
    // Create a big word-wrapped UILabel 
    cell = [tableView dequeueReusableCellWithIdentifier:@"libertyCell"]; 
    if (!cell) { 
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"libertyCell"] autorelease]; 
        [cell addSubview:[[UILabel alloc] initWithFrame:CGRectMake(20.0f, 10.0f, 280.0f, 330.0f)]]; 
    } 
    UILabel *sv = [[cell subviews] lastObject]; 
    sv.text =  @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation."; 
    sv.textAlignment = UITextAlignmentCenter; 
    sv.lineBreakMode = UILineBreakModeWordWrap; 
    sv.numberOfLines = 9999; 
    return cell; 
} 

...调整“sv”UILabel子视图和“单元格”UITableViewCell的大小,使其大小足以适应文本(并且可以使用更多或更少的文本以及其他类型的文本对齐)? 我查看了UILabel textRectForBounds:limitedToNumberOfLines:方法,但文档声明不应该直接调用它(只应该被覆盖)。 我尝试了UIView sizeToFit方法,但没有成功。

更新:我问了一个关于我的NSString -sizeWithFont:forWidth:lineBreakMode:方法问题的新问题。


我不得不这样做,我扩展了UILabel为我做到这一点:

@interface UILabel (BPExtensions)
- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth;
@end

@implementation UILabel (BPExtensions)


- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
    self.lineBreakMode = NSLineBreakByWordWrapping;
    self.numberOfLines = 0;
    [self sizeToFit];
}
@end

然后有一个标签有一个可变的多行高度,但只有一个固定的宽度:

[myLabel sizeToFitFixedWidth:kSomeFixedWidth];


您应该使用NSString的-sizeWithFont:forWidth:lineBreakMode:方法来检索标签的关联尺寸标准。


另外,如果要使用该代码,请将numberOfLines属性更改为0

链接地址: http://www.djcxy.com/p/28197.html

上一篇: Sizing a UILabel to fit?

下一篇: How to adjust a label size to fit the length of the text