44

在我的 iPad 应用程序中,我注意到 iOS 6 和 iOS 7 之间的 UITextFields 行为不同。

我创建 UITextField 如下:

UIButton *theButton = (UIButton*)sender;
UITextField *textField = [[UITextField alloc] initWithFrame:[theButton frame]];

[textField setDelegate:self];
[textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[textField setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];

textField.textAlignment = UITextAlignmentRight;
textField.keyboardType = UIKeyboardTypeDefault;

...

[textField becomeFirstResponder];

在 iOS 6 中,当我键入“hello world”时,当我在“hello”之后点击空格键时,光标会前进一个空格。

在 iOS 7 中,当我按下空格键时光标不会前进。但是,当我在“world”中键入“w”时,它会显示空格和 w。

在 iOS 7 中按下空格键时如何前进光标?

更新:

如果我将 textField.textAlignment 更改为 UITextAlignmentLeft,则该空间会出现在 iOS 7 中。如果可能的话,我希望它保持右对齐。

4

14 回答 14

49

这将是一个 hack,但如果你真的需要它来查看 iOS6 的方式,你可以用不间断的空间替换空间,因为它是写的。它被区别对待。示例代码可能如下所示:

- (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"with来转换文本。@" "

于 2013-11-21T18:49:27.173 回答
14

上面所有的答案都很棒而且很有指示性!特别感谢下面的含义问题回答。这是一个经过测试的Swift 2.0版本。请记住将UITextField的委托分配给您的 ViewController!快乐编码。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (textField == self.desiredTextField) {
        var oldString = textField.text!
        let newRange = oldString.startIndex.advancedBy(range.location)..<oldString.startIndex.advancedBy(range.location + range.length)
        let newString = oldString.stringByReplacingCharactersInRange(newRange, withString: string)
        textField.text = newString.stringByReplacingOccurrencesOfString(" ", withString: "\u{00a0}");
        return false;
    } else {
        return true;
    }

}

--

这里是 Swift 3!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField == self.textfield) {
        let oldString = textField.text!
        let newStart = oldString.index(oldString.startIndex, offsetBy: range.location)
        let newEnd = oldString.index(oldString.startIndex, offsetBy: range.location + range.length)
        let newString = oldString.replacingCharacters(in: newStart..<newEnd, with: string)
        textField.text = newString.replacingOccurrences(of: " ", with: "\u{00a0}")
        return false;
    } else {
        return true;
    }
}
于 2016-03-05T05:30:03.083 回答
13

您必须用不间断空格替换普通空格。最好为此触发更改事件的操作:

  1. UIControlEventEditingChanged在某个地方为您的文本字段上的事件添加一个操作:

    [myTextField addTarget:self action:@selector(replaceNormalSpacesWithNonBreakingSpaces)
                      forControlEvents:UIControlEventEditingChanged];
    
  2. 然后实现replaceNormalSpacesWithNonBreakingSpaces方法:

    - (void)replaceNormalSpacesWithNonBreakingSpaces
    {
        self.text = [self.text stringByReplacingOccurrencesOfString:@" "
                                                         withString:@"\u00a0"];
    }
    

这比 using 更安全textField:shouldChangeCharactersInRange:replacementString:,因为如果您NO从此方法返回,您实际上是在说不应更改指定的文本。这将导致不触发更改事件(如 IBActionstextFieldEditingChanged:或 UITextField 的事件)。UIControlEventEditingChanged

到处修复它:

如果您希望对所有 UITextFields 进行此修复,您可以创建一个类别,在启动 UITextField 时添加这些事件操作。在下面的示例中,我还将在编辑结束时将不间断空格改回正常空格,以便在其他地方使用数据时不会出现不间断空格的可能问题。请注意,此示例使用方法混合,因此它可能看起来有点奇怪,但它是正确的。

头文件:

//  UITextField+RightAlignedNoSpaceFix.h

#import <UIKit/UIKit.h>

@interface UITextField (RightAlignedNoSpaceFix)
@end

实现文件:

//  UITextField+RightAlignedNoSpaceFix.m

#import "UITextField+RightAlignedNoSpaceFix.h"

@implementation UITextField (RightAlignedNoSpaceFix)

static NSString *normal_space_string = @" ";
static NSString *non_breaking_space_string = @"\u00a0";

+(void)load
{
    [self overrideSelector:@selector(initWithCoder:)
              withSelector:@selector(initWithCoder_override:)];

    [self overrideSelector:@selector(initWithFrame:)
              withSelector:@selector(initWithFrame_override:)];
}

/**
 * Method swizzles the initWithCoder method and adds the space fix
 * actions.
 */
-(instancetype)initWithCoder_override:(NSCoder*)decoder
{
    self = [self initWithCoder_override:decoder];
    [self addSpaceFixActions];
    return self;
}

/**
 * Method swizzles the initWithFrame method and adds the space fix
 * actions.
 */
-(instancetype)initWithFrame_override:(CGRect)frame
{
    self = [self initWithFrame_override:frame];
    [self addSpaceFixActions];
    return self;
}

/**
 * Will add actions on the text field that will replace normal 
 * spaces with non-breaking spaces, and replaces them back after
 * leaving the textfield.
 *
 * On iOS 7 spaces are not shown if they're not followed by another
 * character in a text field where the text is right aligned. When we
 * use non-breaking spaces this issue doesn't occur.
 *
 * While editing, the normal spaces will be replaced with non-breaking
 * spaces. When editing ends, the non-breaking spaces are replaced with
 * normal spaces again, so that possible problems with non-breaking
 * spaces won't occur when the data is used somewhere else.
 */
- (void)addSpaceFixActions
{

    [self addTarget:self action:@selector(replaceNormalSpacesWithNonBreakingSpaces)
               forControlEvents:UIControlEventEditingDidBegin];

    [self addTarget:self action:@selector(replaceNormalSpacesWithNonBreakingSpaces)
               forControlEvents:UIControlEventEditingChanged];

    [self addTarget:self action:@selector(replaceNonBreakingSpacesWithNormalSpaces)
               forControlEvents:UIControlEventEditingDidEnd];

}

/**
 * Will replace normal spaces with non-breaking spaces.
 */
- (void)replaceNormalSpacesWithNonBreakingSpaces
{
    self.text = [self.text stringByReplacingOccurrencesOfString:normal_space_string
                                                     withString:non_breaking_space_string];
}

/**
 * Will replace non-breaking spaces with normal spaces.
 */
- (void)replaceNonBreakingSpacesWithNormalSpaces
{
    self.text = [self.text stringByReplacingOccurrencesOfString:non_breaking_space_string
                                                     withString:normal_space_string];
}

@end
于 2014-03-19T16:26:47.100 回答
5

我想出了一个解决方案,它继承 UITextField 类并执行交换,而不需要到处复制和粘贴代码。这也避免了使用方法嘶嘶声来解决这个问题。

@implementation CustomTextField

-(id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];

    if( self ) {

        [self addSpaceFixActions];
    }

    return self;
}

- (void)addSpaceFixActions {
    [self addTarget:self action:@selector(replaceNormalSpaces) forControlEvents:UIControlEventEditingChanged];
    [self addTarget:self action:@selector(replaceBlankSpaces) forControlEvents:UIControlEventEditingDidEnd];
}


//replace normal spaces with non-breaking spaces.
- (void)replaceNormalSpaces {
    if (self.textAlignment == NSTextAlignmentRight) {
        UITextRange *textRange = self.selectedTextRange;
        self.text = [self.text stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"];
        [self setSelectedTextRange:textRange];
    }
}

//replace non-breaking spaces with normal spaces.
- (void)replaceBlankSpaces {
    self.text = [self.text stringByReplacingOccurrencesOfString:@"\u00a0" withString:@" "];
}
于 2015-01-21T21:22:36.843 回答
5

这是一个始终有效的解决方案,也适用于粘贴和编辑(即当您可以添加/删除具有多个空格的文本时)。

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"];

    return NO;
}

不用担心stringByReplacingOccurrencesOfString每次做的表现;相对于 CPU 速度,UI 中的文本非常短。

然后,当您真正想从文本字段中获取值时:

NSString* text = [textField.text stringByReplacingOccurrencesOfString:@"\u00a0" withString:@" "];

所以这是一个很好的对称。

于 2014-03-05T22:44:15.067 回答
4

斯威夫特 4 版本:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
    if var text = textField.text, range.location == text.count, string == " " {
        let noBreakSpace: Character = "\u{00a0}"
        text.append(noBreakSpace)
        textField.text = text
        return false
    }
    return true
}
于 2018-06-22T13:35:14.393 回答
4

将三唑坦的答案转换为 Swift3 。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{

    if (range.location == textField.text?.characters.count && string == " ") {
        let noBreakSpace: Character = "\u{00a0}"
        textField.text = textField.text?.append(noBreakSpace)
        return false
    }
    return true
}
于 2017-01-24T09:41:35.270 回答
3

老问题,但上述所有解决方案似乎都过于复杂。这是我解决问题的方法:

我订阅了两个文本字段事件->

  • TextFieldEditingDidBegin
  • TextFieldEditingEnded

在 TextFieldEditingDidBegin 上,我简单地将 textField.textAlignment 设置为 UITextAlignmentLeft。在 TextFieldEditingEnded 上,我将 textField.textAlignment 设置回 UITextAlignmentRight。

这对我来说完美无缺,我觉得它不是黑客。希望能帮助到你!

于 2014-09-05T20:23:15.657 回答
1

通过用不间断空格替换空格来修复右对齐的文本空格

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.textAlignment == NSTextAlignmentRight) {
        NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
        textField.text = [text stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"];

        UITextPosition *startPos = [textField positionFromPosition:textField.beginningOfDocument offset:range.location + string.length];
        UITextRange *textRange = [textField textRangeFromPosition:startPos toPosition:startPos];
        textField.selectedTextRange = textRange;

        return NO;
    }

    return YES;
}

反之亦然

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    // Replacing non-breaking spaces with spaces and remove obsolete data
    NSString *textString = [[textField.text stringByReplacingOccurrencesOfString:@"\u00a0" withString:@" "] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    textField.text = textString;
}
于 2014-12-02T15:52:21.800 回答
1

我通过使用左对齐的文本字段在我的应用程序中解决了这个问题,然后使用 AutoLayout 将整个文本字段向右对齐。这模拟了一个右对齐的文本字段并处理尾随空格而不会弄乱空格字符等。

这种方法的主要障碍是 UITextField 不会随着文本的变化而更新其固有的内容大小。为了解决这个问题,我将 UITextField 子类化为在文本更改时自动计算内在内容大小。这是我的子类:

@implementation PLResizingTextField

- (instancetype)init {
    self = [super init];
    if(self) {
        [self addTarget:self action:@selector(invalidateIntrinsicContentSize) forControlEvents:UIControlEventEditingChanged];
    }
    return self;
}

- (CGSize)intrinsicContentSize {
    CGSize size = [super intrinsicContentSize];
    NSString *text = self.text.length ? self.text : self.placeholder;

    CGRect rect = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX,CGFLOAT_MAX)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:self.font}
                                     context:nil];
    size.width = CGRectGetWidth(rect);

    return size;
}

@end

这是我使用 PureLayout 库的自动布局代码的片段:

[textField autoPinEdgeToSuperviewEdge:ALEdgeTrailing
                            withInset:10];
[textField autoPinEdge:ALEdgeLeading
                toEdge:ALEdgeTrailing
                ofView:cell.textLabel
            withOffset:10
              relation:NSLayoutRelationGreaterThanOrEqual];
[textField setContentHuggingPriority:UILayoutPriorityDefaultHigh
                             forAxis:UILayoutConstraintAxisHorizontal];

这里需要注意的要点:

  1. 在文本字段上设置内容拥抱优先级
  2. 使用NSLayoutRelationGreaterThanOrEqual文本字段的左边缘与其左侧的视图(或超级视图的左边缘)之间的关系。
于 2015-06-09T23:52:33.393 回答
1
extension UITextField {

    /// runtime key
    private struct AssociatedKeys {

        ///
        static var toggleState: UInt8 = 0
    }

    /// prevent multiple fix
    private var isFixedRightSpace: Bool {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.toggleState) as? Bool ?? false
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.toggleState, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        if self.textAlignment == .right && !isFixedRightSpace {
            self.isFixedRightSpace = true
            self.addTarget(self, action: #selector(replaceNormalSpacesWithNonBreakingSpaces(textFiled:)), for: UIControl.Event.editingChanged)
        }

        return super.hitTest(point, with: event)
    }

    /// replace space to \u{00a0}
    @objc private func replaceNormalSpacesWithNonBreakingSpaces(textFiled: UITextField) {

        if textFiled.markedTextRange == nil && textFiled.text?.contains(" ") ?? false {

            /// keep current range
            let editRange = selectedTextRange
            textFiled.text = textFiled.text?.replacingOccurrences(of: " ", with: "\u{00a0}")
            /// reset this range
            selectedTextRange = editRange
        }
    }
}

于 2018-12-05T07:11:33.077 回答
1

这是@Jack Song 的回答中的 Swift 3

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField == self.textfield) {
        let oldString = textField.text!
        let newStart = oldString.index(oldString.startIndex, offsetBy: range.location)
        let newEnd = oldString.index(oldString.startIndex, offsetBy: range.location + range.length)
        let newString = oldString.replacingCharacters(in: newStart..<newEnd, with: string)
        textField.text = newString.replacingOccurrences(of: " ", with: "\u{00a0}")
        return false;
    } else {
        return true;
    }
}
于 2017-02-02T18:58:05.850 回答
0

我的以下解决方案还解决了在字符串的中间或开头键入空格时光标跳到末尾的问题。现在也可以正确处理粘贴字符串。

我还检查了电子邮件地址字段和其他检查,但有趣的部分是最后一部分。它对我来说非常有效,还没有发现问题。

您可以直接将其复制/粘贴到您的项目中。不要忘记实现 didBeginEditing 和 didEndEditing 以用不间断空格替换空格并返回!

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.textAlignment != NSTextAlignmentRight) //the whole issue only applies to right aligned text
        return YES;

    if (!([string isEqualToString:@" "] || string.length > 1)) //string needs to be a space or paste action (>1) to get special treatment
        return YES;

    if (textField.keyboardType == UIKeyboardTypeEmailAddress) //keep out spaces from email address field
    {
        if (string.length == 1)
            return NO;
        //remove spaces and nonbreaking spaces from paste action in email field:
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        string = [string stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];
    }

    //special treatment starts here
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"];
    UITextPosition *beginning = textField.beginningOfDocument;
    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    UITextPosition *start = [textField positionFromPosition:beginning offset:range.location+string.length];
    UITextPosition *end = [textField positionFromPosition:start offset:range.length];
    UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end];
    [textField setSelectedTextRange:textRange];

    return NO;
}
于 2014-11-30T18:54:59.757 回答
0

我已经使用Jack SongSwift 2的回答有一段时间了,直到我意识到非制动空格在其他地方以 HTML 呈现时会出现问题,并且 UITextView 本身中的换行也会变得混乱。所以,我改进了解决方案,立即清理非括号字符。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if (textField == self.desiredTextField) {
       var oldString = textView.text!
       oldString = oldString.stringByReplacingOccurrencesOfString("\u{00a0}", withString: " ");
       let newRange = oldString.startIndex.advancedBy(range.location)..<oldString.startIndex.advancedBy(range.location + range.length)
       let alteredText = text.stringByReplacingOccurrencesOfString(" ", withString: "\u{00a0}")
       textView.text = oldString.stringByReplacingCharactersInRange(newRange, withString: alteredText)
       return false;
    } else {
       return true;
    }
}
于 2016-09-12T13:46:40.050 回答