1

在我看来,我正在处理的代码应该是这样写的:

    if (!instructions)
{
    instructions = [[UITextView alloc] init];
    instructions.backgroundColor=[UIColor clearColor];
    instructions.font = [UIFont fontWithName:@"Helvetica Neue" size:12];
    instructions.editable=NO;
    instructions.text = @"\nFor millennia, the Japanese haiku has allowed great\nthinkers to express their ideas about the world in three\nlines of five, seven, and five syllables respectively.";

//THIS IS THE RELEVANT LINE:
    NSString *t = @"thinkers to express their ideas about the world in three"; //Using this to set width since it's the longest line of the string.

    CGSize thisSize = [t sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:12]];
    float textWidth = thisSize.width;
    const int INSTRUCTIONS_HEIGHT=10; //I know this is an ugly hack.
    float textHeight = thisSize.height*INSTRUCTIONS_HEIGHT;
    instructions.frame = CGRectMake(screenWidth/2-textWidth/2, screenHeight/2-textHeight/2, textWidth, textHeight);
}

但输出看起来像这样,行必须环绕:

在此处输入图像描述

当我调整代码以在设置宽度的行中添加一些字符时:

    {
    instructions = [[UITextView alloc] init];
    instructions.backgroundColor=[UIColor clearColor];
    instructions.font = [UIFont fontWithName:@"Helvetica Neue" size:12];
    instructions.editable=NO;
    instructions.text = @"\nFor millennia, the Japanese haiku has allowed great\nthinkers to express their ideas about the world in three\nlines of five, seven, and five syllables respectively.";

//THIS IS THE LINE I CHANGED:
    NSString *t = @"thinkers to express their ideas about the world in three lin"; //

    CGSize thisSize = [t sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:12]];
    float textWidth = thisSize.width;
    const int INSTRUCTIONS_HEIGHT=6; //Since there's no wraparound here I could reduce this number.
    float textHeight = thisSize.height*INSTRUCTIONS_HEIGHT;
    instructions.frame = CGRectMake(screenWidth/2-textWidth/2, screenHeight/2-textHeight/2, textWidth, textHeight);
}

输出看起来像我想要的:

在此处输入图像描述

为什么“思想家在三个方面表达他们对世界的想法”这一行不适合设置在“思想家在三个方面表达他们对世界的想法”这一行宽度处的文本视图?

(显然,我需要学习如何在屏幕上定位事物。例如,我还没有弄清楚“中心”,我怀疑这会解决我的很多问题。但这就是我正在使用的现在,我很好奇。)

4

3 回答 3

3

UITextView 默认有一些填充。如果你愿意,你可以摆脱它:如何在 UITextView 中丢失边距/填充?

于 2013-01-15T00:23:20.370 回答
3

您需要将 sizeWithFont 限制为文本视图的宽度。

就像是:

drawnSize = [t sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:12]
                 constrainedToSize:CGSizeMake(instructions.frame.size.width, 3000)
                 lineBreakMode:NSLineBreakByWordWrapping ] ;

您可能还需要从文本视图中获取插图并从宽度中减去它们:

UIEdgeInsets edgeInsets = instructions.contentInset;
CGFloat totalwidth = instructions.frame.size.width - edgeInsets.left - edgeInsets.right;
于 2013-01-15T00:23:53.070 回答
3

一个原因是您正在使用文本视图。你所做的对 UILabel 来说很好。并且标签可能有多行。因此,如果您真的不需要文本视图来滚动文本,那么请考虑使用标签。

我不记得确切的值。但是对于文本视图,请考虑一些模糊昆虫值,其中文本本身的实际宽度/空间小于文本视图。

于 2013-01-15T00:23:56.470 回答