How to calculate NSRange NSString at a specific position in a UITextView

When I click on a specific position in a UITextView, I want to get the NSString substring that is shown in the string.

I have, for example, a UITextView that displays a row using 16 rows. When I click on the position (200, 150), I want the substring shown by the UITextView on this crane.

Any suggestions on how to achieve this?

+3
source share
2 answers

, . view IBOutlet UITextView , viewcontroller UITextViewDelegate. UITextView FileOwner InterfaceBuilder , UITextView FileOwner.

@interface StackOverFlowViewController : UIViewController<UITextViewDelegate> {

    IBOutlet UITextView *textView;
}
@end

UIViewController UITextViewDelegate.

- (void)textViewDidChangeSelection:(UITextView *)aTextView {

  NSRange rangeOfSelection = textView.selectedRange;
  NSString *selectedText = [textView.text substringWithRange:rangeOfSelection];
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selection Changed" message:selectedText delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [alert show];
  [alert release];
}

, UITextView, . selectedRange UITextView, NSRange, . UITextView .

UIAlertView textViewDidChangeSelection,

+1

UITextView , . , . (resignFirstResponder) KeyboardDidShow, NSRange , UITextView . UITextView , , , TextViewDidChangeSelection, , NSRange .

, , NSRange . :

  • , :

    // UIView * systemKeyboard;

    //touch textView , textView . KeyboardDidShow

    - (BOOL) textViewShouldBeginEditing: (UITextView) textView {   NSLog (@ "textViewShouldBeginEditing" );    (! systemKeyboard) {       UIWindow window1 = [UIApplication sharedApplication].windows [1];       for (int = 0; < window1.subviews.count; ++) {           UIView * keyBoard1 = window1.subviews [i];           if ([keyBoard1 isKindOfClass: NSClassFromString (@ "UIInputSetContainerView" )]) {               systemKeyboard = keyBoard1;//               break;          }       }   }   CGRect rec1 = systemKeyboard.frame;   systemKeyboard.frame = CGRectMake (2000, 2000, rec1.size.width, rec1.size.height);   return YES; }

  • NSRange textViewDidChangeSelection:

    //touch textView - (void) textViewDidChangeSelection: (UITextView *) textView {   NSLog (@ "textViewDidChangeSelection" );    NSRange = [sermonTextView selectedRange]; }

  • , :

    // , , , , . - (BOOL) searchBarShouldBeginEditing: (UISearchBar *) searchBar {   NSLog (@ "searchBarShouldBeginEditing" );    (systemKeyboard) {       CGRect rec1 = systemKeyboard.frame;       systemKeyboard.frame = CGRectMake (0, 0, rec1.size.width, rec1.size.height);       // [sermonTextView resignFirstResponder];       // [searchBar1 FirstResponder];   }   .........   return YES; }

0

Source: https://habr.com/ru/post/1759644/


All Articles