UITextView更改selectRange始终崩溃

问题描述:

当用户单击textView中的段落时,我想将光标更改为linebreak,但是当我更改selectionRange时总是失败。 我知道原因,但我必须更改selectedRangefunc: textViewDidChangeSelection:(UITextView*)textViewUITextView更改selectRange始终崩溃

如何更改selectedRange?

这里是代码

-(void)textViewDidChangeSelection:(UITextView *)textView 

// paragLocations: it contain all "\n" locations 
NSArray* paragLocations = [self ParagraphLocationsWithText:textView Pattern:translatePragraphLinebreak]; 

//  location :According to user selection,The nearest "\n" location 
NSUInteger nearestLocation = [self ClickParagraphEndBreakLoctionWithSelectLocation:textView.selectedRange.location withParagLocations:paragLocations]; 
//Then 
//1. here I change the textView.selectedRange 
textView.selectedRange = NSMakeRange(nearestLocation, 0); 
//2. here I change the cursorPosition 
CGFloat cursorPosition = [self caretRectForPosition:textView.selectedTextRange.start].origin.y; 
[textView setContentOffset:CGPointMake(0, cursorPosition) animated:YES]; 
// but In step 1 ,It changed textView.selectedRange,So this func will do it again,and then again,until the nearestLocation became the paragLocations.lastObject. 
/* 
     so the question is how to break this Infinite loop ? 
     should I change selectedRange In this func? 
     I want to changed the selectedRange base on User select In textview 
*/ 

对不起我的英文不好。

+0

它是“更改** selectionRange **始终失败”或selectedRange ..? – vaibhav

+0

我编辑的问题来解释清楚 –

你可以试试下面的代码,它对我很好。

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

     UITextRange *selectRange = [textView selectedTextRange]; 
     NSString *selectedText = [textView textInRange:selectRange]; 
    } 
+0

我只是想改变func中的selectRange,而不是 –