gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:23:28 28 4
gpt4 key购买 nike

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

    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

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

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

最佳答案

您需要将 sizeWithFont 限制为 TextView 的宽度。

就像是:

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

您可能还需要从 TextView 中获取插图并从宽度中减去它们:
UIEdgeInsets edgeInsets = instructions.contentInset;
CGFloat totalwidth = instructions.frame.size.width - edgeInsets.left - edgeInsets.right;

关于ios - 为什么我的 NSString 不适合使用我的 NSString 宽度创建的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329166/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com