2014-12-06 17 views
3

當用戶輸入新行時,如何將自動縮進添加到UITextView?例如:如何在用戶輸入新行時將自動縮進添加到UITextView?

line1 
    line2 <user has typed "Enter"> 
    <cursor position> 
    line3 <user has typed "Enter"> 
    <cursor position> 
+0

誰是那些誰設置弊的單純,善良和實際問題的人呢?討厭他們。 – Dmitry 2014-12-06 18:06:31

+1

是的,我同意。它變得荒謬。 – 2014-12-06 18:18:49

+0

我很快就會爲你解答。 – 2014-12-06 18:19:30

回答

3

雖然看上去好像OP其實也不是尋找在這種情況下標準的壓痕,我要離開這件事對未來的答案者。

下面介紹如何在每次換行符後自動添加縮進。我已經從我近期的answer about automatically adding bullet points at every newline調整了這個答案。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 

    // If the replacement text is "\n" thus indicating a newline... 
    if ([text isEqualToString:@"\n"]) { 

     // If the replacement text is being added to the end of the 
     // text view's text, i.e. the new index is the length of the 
     // old text view's text... 
     if (range.location == textView.text.length) { 
      // Simply add the newline and tab to the end 
      NSString *updatedText = [textView.text stringByAppendingString:@"\n\t"]; 
      [textView setText:updatedText]; 
     } 

     // Else if the replacement text is being added in the middle of 
     // the text view's text... 
     else { 

      // Get the replacement range of the UITextView 
      UITextPosition *beginning = textView.beginningOfDocument; 
      UITextPosition *start = [textView positionFromPosition:beginning offset:range.location]; 
      UITextPosition *end = [textView positionFromPosition:start offset:range.length]; 
      UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end]; 

      // Insert that newline character *and* a tab 
      // at the point at which the user inputted just the 
      // newline character 
      [textView replaceRange:textRange withText:@"\n\t"]; 

      // Update the cursor position accordingly 
      NSRange cursor = NSMakeRange(range.location + @"\n\t".length, 0); 
      textView.selectedRange = cursor; 

     } 

     // Then return "NO, don't change the characters in range" since 
     // you've just done the work already 
     return NO; 
    } 

    // Else return yes 
    return YES; 
} 
+0

非常感謝您的回答!但是我怎麼能把這麼多的空間放在上面? – Dmitry 2014-12-06 18:32:19

+0

它的工作原理。但我怎樣才能防止光標位置?它總是在'[textView setText:mutableText]'調用後的文本末尾顯示。 – Dmitry 2014-12-15 13:18:36

+0

@Altaveron哦,當然...你可以使用'textView.selectedRange'設置光標位置。我會盡快更新,以便更具體... – 2014-12-15 13:59:36

2

對於第一行,你會寫這樣的代碼:

- (void)textViewDidBeginEditing(UITextView *)textView 
{ 
    if ([textView.text isEqualToString:@""]) 
    { 
     [textView setText:@"\t"]; 
    } 
} 
相關問題