【问题标题】:Rightalignment UITextfield's cursor go left after enter a space输入空格后右对齐UITextfield的光标向左移动
【发布时间】:2016-07-14 14:42:14
【问题描述】:
  1. 我将 UITextfield 设置为 NSTextAlignmentRight ,并且它的光标正常位于右端。

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

  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;
}

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

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

【问题讨论】:

    标签: ios objective-c uitextfield text-alignment


    【解决方案1】:
    - (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 协议方法,所以在您的示例中,上述方法将在 [textField setDelegate:self] 指定的视图控制器中。

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

    参考:Right aligned UITextField spacebar does not advance cursor in iOS 7

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多