当选择(触摸)UITextView
时,我尝试移动光标以模拟UITextField占位符
事物。
我希望光标位于第一行的开头。我的问题是,[someTextField setSelectedRange]
无法可靠地工作。当我在 textView:shouldChangeTextInRange:replacementText:
中调用它时,它会按预期工作。但只有当用户开始输入时才会调用此方法。当 UITextView
成为第一响应者时,我使用 textViewDidBeginEditing:
移动光标:
- (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:
中无法正常工作吗?
感谢您的帮助!
最佳答案
实际上有一个非常简单的方法可以实现这一点。
// 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);
希望这有帮助。
关于objective-c - 在 UITextView 中移动光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348840/