如何在UITextView中获取文本rect

时间:2014-04-18 12:21:32

标签: ios objective-c cocoa-touch uitextview

我在UItextView中遇到文本的获取框架矩形我正在使用此代码`

UITextPosition *Pos2 = [textView positionFromPosition: drawTextView.endOfDocument offset: 0];
    UITextPosition *Pos1 = [textView positionFromPosition: drawTextView.endOfDocument offset: -[textView.text length]];

    UITextRange *range = [textView textRangeFromPosition:Pos1 toPosition:Pos2];

    CGRect result1 = [textView firstRectForRange:(UITextRange *)range ];

but it returns me origin =(x = + Inf,y = + Inf)size =(width = 0,height = 0)`

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码

来获取它
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{   
    CGRect rc = [textView bounds];
    rc = [textView convertRect:rc toView:superViewOfTextView];
    .
    .
    .
    //Put your logic.

}

要获取文字宽度和高度,请使用

CGFloat width = [self.txtView.text length];
CGFloat height = [self.txtView.text sizeWithFont:setFontWithSize constrainedToSize:self.txtView.frame.size.width lineBreakMode:NSLineBreakByWordWrapping];   

答案 1 :(得分:1)

检查一下:

CGRect size = [myTextView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, Max_height)
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                  attributes:attributesDictionary
                                                     context:nil];
NSLog(@"height : %@" size.height);