1

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

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

4

1 回答 1

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);
于 2013-06-03T05:27:57.070 回答