2012-02-19 171 views
1

當您選擇(觸摸)UITextView來模擬UITextField placeholder事物的種類時,我嘗試移動光標。在UITextView中移動光標

我希望光標位於第一行的開頭。我的問題是,[someTextField setSelectedRange]不能可靠地工作。當我在textView:shouldChangeTextInRange:replacementText:中調用它時,它應該可以正常工作。但是這種方法只在用戶開始輸入時才被調用。我使用textViewDidBeginEditing:移動光標時UITextView成爲第一個響應者:

- (void)textViewDidBeginEditing:(UITextView *)textView 
{ 
    if (textView == self.descriptionText) { 
     CustomTextView* customTV = (CustomTextView *)textView; 
     if ([customTV.text isEqualToString:customTV.placeholder]) { 
      // text in text view is still the placeholder -> move cursor to the beginning 
      customTV.text = customTV.placeholder; 
      customTV.textColor = [UIColor lightGrayColor]; 
      customTV.selectedRange = NSMakeRange(0, 0); 
     } 
    } 
} 

任何想法,爲什麼customTV.selectedRange = NSMakeRange(0, 0);textViewDidBeginEditing:正常工作?

感謝您的幫助!

+0

您是否找到解決方案? – Legolas 2012-04-13 15:46:22

回答

2

其實有一個非常簡單的方法來完成這個。

// Count the characters on screen 
    NSMutableString *numOfChar = [self.myTextField.text mutableCopy]; 

    // Skip that many characters to the left 
    self.myTextField.selectedRange = NSMakeRange(self.myTextField.selectedRange.location-[numOfChar length], 0); 

希望這會有所幫助。