在UITextView中移动光标

时间:2012-02-19 11:44:20

标签: objective-c ios cocoa-touch uitextview

当我选择(触摸)UITextView时,我会尝试移动光标来模拟UITextField placeholder的事物。

我希望光标位于第一行的开头。我的问题是,[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:无法正常使用的任何想法?

感谢您的帮助!

1 个答案:

答案 0 :(得分: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);

希望这有帮助。