ios - Rightalignment UITextfield 的光标在输入空格后向左移动

标签 ios objective-c uitextfield text-alignment

  1. 我将 UITextfield 设置为 NSTextAlignmentRight ,它的光标正常位于右端。
    enter image description here

  2. 当我输入空格时,光标会转到 UITextfield 的左端。
    enter image description here

  3. 我尝试通过实现 UITextFieldDelegate 方法来解决这个问题

像这样:

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  if (range.location == 0 && [string isEqualToString:@" "]) {
    return NO;
  }
return YES;
}

但是有点乱,我不能为第一个字符输入空格。

是否有更好的解决方案来解决这个问题?
为什么会出现这个错误?

最佳答案

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // only when adding on the end of textfield && it's a space
    if (range.location == textField.text.length && [string isEqualToString:@" "]) {
        // ignore replacement string and add your own
        textField.text = [textField.text stringByAppendingString:@"\u00a0"];
        return NO;
    }
    // for all other cases, proceed with replacement
    return YES;
}

如果不清楚,textField:shouldChangeCharactersInRange:replacementString: 是一个 UITextFieldDelegate 协议(protocol)方法,因此在您的示例中,上述方法将位于 [textField setDelegate:self] 指定的 View Controller 中。

如果您想要返回常规空格,显然还需要记住在从文本字段中获取字符串时将出现的 @"\u00a0"替换为 @""以将文本转换回来

引用: Right aligned UITextField spacebar does not advance cursor in iOS 7

关于ios - Rightalignment UITextfield 的光标在输入空格后向左移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243711/

相关文章:

objective-c - 更新 MKMapView (iPhone) 的中心点和缩放

编辑时iOS UITextField未清除

ios - UITextField 只接受一位小数点,小数点前最多 3 位,小数点后最多 2 位

ios - 用 UIBezierPath 绘制虚线的顶部和底部

ios - Dropbox 错误 OAuth 请求 "Error 403"

iphone - 处理 Storyboard 中 View Controller 之间的模态转场

ios - 具有清晰背景的 UISlider 拇指图像在其后面显示轨道

ios - UITextField 无法正确显示超出范围的文本

ios - 从 Any 向下转换为 Specific 类型

ios - 将多边形拟合在一起