0

我有一个使用 Xcode 4.5 构建并在 iOS6 模拟器上运行的简单测试应用程序

它只是一个带有 UIScrollView 的 UIViewController,在 UIScrollView 中只有一个 UILabel。

我在界面构建器中将 UILabel 中的 NumberOfLines 设置为 0,并将其设置为 ScrollView 中的全宽 - 但高度只有大约 30 个点。我还将 UIScrollView 设置为仅垂直滚动。我为两个 UI 组件设置了几个 IBOutlets,并将文件的所有者设置为 UIScrollView 的委托(并放在 UIViewController 标头上。)

在 viewDidLoad 中,我只是将标签的文本设置为一个不错的长字符串。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.txtLabel2.text = @"`Twas brillig, and the slithy toves - Did gyre and gimble in the wabe: - All mimsy were the borogoves, - And the mome raths outgrabe. ";
}

然后在 ViewDidAppear 中,我将滚动视图的内容大小设置为 UILabel 的大小:

-(void)viewDidAppear:(BOOL)animated
{
    self.scrollView.contentSize = self.txtLabel2.bounds.size;
}

这似乎运作良好 - UILabel 会自动调整其高度,并将滚动视图设置为正确的高度并很好地滚动文本。伟大的。

但是,我显然在这里做错了 - 因为如果我进入界面构建器并将 UILabel 的字体大小从默认值(17.0)更改为任何其他值 - 它就会停止工作。标签不再调整大小并在第一行被截断。

我尝试手动调整 UILabel 的大小 - 例如使用此处建议的解决方案:

调整 UILabel 的大小以适合?

并在我设置内容时使用扩展名:

self.txtLabel2.text = @"`Twas brillig, and the slithy toves - Did gyre and gimble in the wabe: - All mimsy were the borogoves, - And the mome raths outgrabe. ";
//use the current width - resize the height
[self.txtLabel2 sizeToFitFixedWidth:self.txtLabel2.bounds.size.width];

但这似乎没有任何效果。

我不明白为什么改变字体大小应该改变 UILabel 自动调整大小的行为,我不知道为什么手动设置 UILabel 的大小没有效果。这里发生了什么?(还有——我应该做些什么不同的事情,这样我一开始就不会陷入这种混乱!)

4

1 回答 1

0

我不知道为什么您的代码不起作用,因为有多种可能性但是跟随代码是您的代码的不错选择

int scrollViews_fixed_width = self.scrollView.bounds.size.width;
self.txtLabel2.lineBreakMode = UILineBreakModeWordWrap; 
self.txtLabel2.numberOfLines = 0;

UIFont *font = [UIFont fontWithName:@"Helvetica" size:14.0];//Choose Your Font this is default font
CGSize constraintSize = CGSizeMake(scrollViews_fixed_width, 555);// Choose big value max possible height of textLabel or leave it 555 this will be enough
float  calculatedHeight = [@"Your Long String" sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap].height;
self.txtLabel2.frame = CGRectMake(0,0,scrollViews_fixed_width,calculatedHeight);
self.scrollView.contentSize = CGSizeMake(scrollViews_fixed_width, calculatedHeight);

您可能需要为高度添加一些偏移量,因为上面的代码计算不考虑空格投注线,如果您对上述内容感到满意,请不要为此使用 foll 实现使用小字符串计算单行的高度,然后使用 no_of_lines = computedHeight/ single_line_height_calculated_using_small_string 然后添加一些额外的偏移到高度取决于没有。行数

于 2012-10-10T18:26:42.713 回答