iphone -Objective C get tap position in UITextView

    技术2024-08-06  60

     

    I find some code about getting position from UITextView, but the guy didn't 

    give the full code,  I fill up the missing code(the "while loop"), now I can get the position 

    in text view, but this is my first version of this method, might have some bugs.

     

     

    -(CGPoint)getPositionInTextView:(UITextView*) textView{

    CGPoint origin = textView.frame.origin;

    NSString* head = [textView.text substringToIndex:textView.selectedRange.location];

    CGSize initialSize = [head sizeWithFont:textView.font constrainedToSize:textView.contentSize lineBreakMode:UILineBreakModeWordWrap];

    NSUInteger startOfLine = [head length];

    while (startOfLine > 0) {

      startOfLine--;

      NSString* reduction=[head substringToIndex:startOfLine];

      CGSize reductionSize = [reduction sizeWithFont:textView.font constrainedToSize:textView.contentSize        lineBreakMode:UILineBreakModeWordWrap];

      if(reductionSize.height<initialSize.height)

        break;  

    }

    NSString* tail = [head substringFromIndex:startOfLine];

    CGSize lineSize = [tail sizeWithFont:textView.font forWidth:textView.contentSize.width lineBreakMode:UILineBreakModeWordWrap];

    CGPoint cursor = origin;

    cursor.x += lineSize.width;

    cursor.y += initialSize.height - lineSize.height;

    return cursor;

    }

     

     

    最新回复(0)