【问题标题】:Getting dimensions of an UITextView获取 UITextView 的尺寸
【发布时间】:2011-03-09 19:49:12
【问题描述】:

如果放置在尺寸为 200 x 460 像素、字体 Courier 的 UITextView 中,我想确定某个文本字符串的尺寸(尤其是行数)。

我尝试调用以下方法来获取一个可以显示的整数。但是,它不起作用(xCode 告诉我我在初始化中有不兼容的类型):

NSString *temp2String;
    temp2String = [NSString stringWithFormat:@"%@",[textView text]];

    int strSize = [temp2String sizeWithFont:@"Courier" constrainedToSize:CGSizeMake(200, 10000)
                   lineBreakMode:UILineBreakModeWordWrap];

    NSString *temp2 = [[NSString alloc] initWithFormat:@"Size of string: %d", strSize];
    textViewSize.text = temp2;
    [temp2 release];

我是初学者,今天早些时候我发布了一个类似的问题,但我仍然无法弄清楚如何让 CGSize 工作并给我所需的答案。任何帮助将不胜感激。

【问题讨论】:

  • 请注意,sizeWithFont: 采用 UIFont,而不是命名字体的字符串。您可以使用[UIFont fontWithName:... size:...] 尝试实例化字体,或使用[UIFont systemFontOfSize:...] 实例化默认字体。详情请见the documentation

标签: iphone objective-c cocoa-touch uitextview


【解决方案1】:

CGSize 是一个结构(来自 CGGeometry.h):

struct CGSize {
  CGFloat width;
  CGFloat height;
};

因此您需要做的就是获取它并显示您需要的任何尺寸;

CGSize strSize = [temp2String sizeWithFont:@"Courier" constrainedToSize:CGSizeMake(200, 10000)
                   lineBreakMode:UILineBreakModeWordWrap];

按照您的示例(注意尺寸以浮点值给出):

NSString *temp2 = [[NSString alloc] initWithFormat:@"Width of string: %f", strSize.width];
textViewSize.text = temp2;
[temp2 release];

【讨论】:

    【解决方案2】:

    CGSize 是一个结构。它包含两个浮点数,分别命名为“高度”和“宽度”。

    CGSize strSize = [temp2String sizeWithFont:@"Courier" constrainedToSize:CGSizeMake(200, 10000)
                       lineBreakMode:UILineBreakModeWordWrap];
    NSLog(@"Height %f, width %f", strSize.height, strSize.width);
    

    【讨论】:

    • 谢谢!很抱歉这个初学者的问题。谢谢你!
    • 别担心,我们都开始了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2010-12-15
    相关资源
    最近更新 更多