【问题标题】:How to calculate width of multiple lines of UITextview?如何计算多行 UITextview 的宽度?
【发布时间】:2013-06-03 05:14:46
【问题描述】:

我有一个UITextView,最多有四行。我想在每一行后面加上UILabels,只覆盖相应行的文本。

那么你们中的任何一位优秀的编码员对我将如何计算每条线的宽度有任何想法吗?

【问题讨论】:

  • 谷歌NSString UIKit extensions,然后 + ,搜索size

标签: iphone objective-c uilabel uitextview lines


【解决方案1】:

试试这个

UIFont *font=[UIFont systemFontOfSize:17.0f];

UILabel *yourLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 80)];
yourLabel.numberOfLines=4;
yourLabel.text=@"Hello\nHulo\nMe\nyou";

CGSize labelSize = [yourLabel.text sizeWithFont:font
                              constrainedToSize:yourLabel.frame.size
                                  lineBreakMode:NSLineBreakByTruncatingTail];
CGFloat singleLineHeight = labelSize.height/yourLabel.numberOfLines;


[self.view addSubview:yourLabel];

单行高度约为 21。

NSLog(@"single line height is %f",singleLineHeight);

对于文本查看请遵循此代码

UITextView *yourView=[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
yourView.font=[UIFont systemFontOfSize:14.0f];
yourView.text    = @"Hello \nmy\n Friend\n Hru? ";

CGSize textViewSize = [yourView.text sizeWithFont:yourView.font
                       constrainedToSize:CGSizeMake(yourView.frame.size.width, FLT_MAX)
                           lineBreakMode:NSLineBreakByTruncatingTail];

[yourView setFrame:CGRectMake(0, 0, textViewSize.width, textViewSize.height)];

[self.view addSubview:yourView];

NSLog(@"single line height is %f",yourView.frame.size.height);

【讨论】:

  • 这非常适合获得高度。我还能做些什么来获得每条线的宽度?
  • 你的意思是你想得到单行的高度和宽度
  • 我想我知道如何获取这些信息了。谢谢,我会接受你的回答。
  • 对于任何感兴趣的人,获取字符串宽度的方法是使用 - (CGSize)sizeWithFont:(UIFont *)font 。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2021-03-16
  • 2011-12-26
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
相关资源
最近更新 更多