如何计算UITextview多行的宽度?

时间:2013-06-03 05:14:46

标签: iphone objective-c uilabel uitextview lines

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

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

1 个答案:

答案 0 :(得分:3)

尝试这个

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