为什么我的NSString不适合用我的NSString宽度创建的框架?

时间:2013-01-15 00:16:49

标签: ios objective-c uitextview

在我看来,我正在处理的代码应该如何编写:

    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);
}

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

enter image description here

当我调整代码时,在设置宽度的行中添加几个字符:

    {
    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);
}

输出看起来像我想要的那样:

enter image description here

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

(显然我有一些学习如何在屏幕上定位事物的方法。我还没有想出“中心”,例如,我怀疑它会解决我的很多问题。但这就是我的意思。我现在正在工作,我很好奇。)

3 个答案:

答案 0 :(得分:3)

UITextView默认有一些填充。如果你愿意,你可以摆脱它:How to lose margin/padding in UITextView?

答案 1 :(得分: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;

答案 2 :(得分:3)

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

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