在UITextField中添加一个不可编辑的文本后缀

8

我有一个UITextField,想在输入的所有文本后面添加一个“?”后缀。

用户不应该能够删除这个“?”或在其右侧添加文本。

如何最好地实现这一点?

9个回答

4

使用UITextFieldDelegate协议来在编辑文本框时更改字符串。以下是一个快速尝试的示例;这需要进一步完善,但应该能让你开始工作。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * currentText = [textField text];
    if( [currentText characterAtIndex:[currentText length] - 1] != '?' ){
        NSMutableString * newText = [NSMutableString stringWithString:currentText];
        [newText replaceCharactersInRange:range withString:string];
        [newText appendString:@"?"];
        [textField setText:newText];
        // We've already made the replacement
        return NO;
    }
    // Allow the text field to handle the replacement 
    return YES;
}

2
您可能需要子类化UITextField并覆盖其drawText:方法,在实际文本的右侧绘制一个额外的“?”字符,而不是将“?”实际添加到视图的文本中。

我喜欢这个解决方案比我自己的解决方案更多。+1 :-) - Tom van der Woerdt
2
Jesse,我们如何绘制这个字符? - user1525984
使用任何常规的UIKit字符串绘制API。 - Jesse Rusak

1

1
我知道我的回答有点晚,但我发现大部分方法对我的情况都不适用。我有一个UITextField,我只想强制添加一个后缀,用户不能编辑它。然而,我不想子类化UITextView,修改它的绘图方式等等。我只想防止用户修改后缀。
首先,在编辑时,我确保在textfield中设置了后缀。这可以根据您的情况以任何方式完成。对于我的情况,我希望从一开始就有后缀,所以当视图加载时,我只需将textfield的文本属性设置为后缀,并存储后缀的长度以备后用。例如:
- (void)viewDidLoad {
    [super viewDidLoad];
    myTextField.text = "suffix";
    _suffixLength = myTextField.text.length;
}

接下来,我按照Josh的建议使用了UITextFieldDelegate协议,但使用字符串的长度和范围来确保没有编辑后缀:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Determine starting location of the suffix in the current string
    int suffixLocation = textField.text.length - _suffixLength;

    // Do not allow replacing anything in/past the suffix
    if (range.location + range.length > suffixLocation)
    {
        return NO;
    }

    // Continue with delegate code...
}

这应该适用于您为文本字段分配的任何后缀值。

0
对于单行的UITextField,您应该能够测量NSString的大小(它在其中有一个测量函数),并将UILabel移动到正确的位置。

0
我已经编写了以下方法来实现在UITextField中放置不可编辑后缀的任务:
    - (void)setSuffixText:(NSString *)suffix
    {
      UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setFont:[UIFont fontWithName:self.tfdDistance.font.fontName size:self.tfdDistance.font.pointSize]];
    [label setTextColor:self.tfdDistance.textColor];
    [label setAlpha:.5];
    [label setText:suffix];

    CGSize suffixSize = [suffix sizeWithFont:label.font];
    label.frame = CGRectMake(0, 0, suffixSize.width, self.tfdDistance.frame.size.height);

    [self.tfdDistance setRightView:label];
    [self.tfdDistance setRightViewMode:UITextFieldViewModeAlways];
}​

0
我会添加一个在编辑完成时调用的方法:
`- (void)editDidFinish {
  NSString* str=[[NSString alloc] init];
  str=myEdit.text;
  [str stringByAppendingString:@"?"];
  myEdit.text=str;
}`

0

好的,我肯定太晚了,但也许我可以帮助别人:

实现这个目标的方法是使用自定义的NSFormatter。以下是文档链接: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/Reference/Reference.html

基本思路是:创建一个NSFormatter子类,并覆盖至少两个工作方法:

-stringObjectForValue:

这将从对象中存储的值生成显示字符串(即在此处添加问号)

-objectValue:ForString:errorDescription

在这里,您需要将显示字符串转换为要存储的对象,即删除问号

然后可以使用格式化程序将数据从存储的对象转换为适合呈现给用户的字符串。 最大的优点是您可以在UI中的任何位置使用格式化程序。它不仅限于某些UI元素,例如覆盖UITextField中的-drawText的解决方案。它只是非常方便。


最好提供一个实际的工作示例,而不是一些关于理论上如何可能的提示。当在UITextField中添加一个不可编辑的后缀时,我真的看不出这该如何使用NSFormatter。 - Joris Mans

0
我在Objective-C中编写的这个类方法可以帮助您向UITextField添加后缀文本。 为了使其正常工作,您需要将UILabel初始化为前缀或后缀,并将其放置在您的UITextFieldLabel中,如下所示:
myTextField.rightView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, myTextField.frame.size.height)];
myTextField.rightViewMode = UITextFieldViewModeAlways;
[MyClass UpdateUITextFieldSuffix:myTextField withString:@"My Suffix!"];

一旦我们将 UILabel 附加到 UITextField 上,您可以使用此类方法来更新文本,这个文本将自动调整大小以适应该字段。
+ (BOOL)UpdateUITextFieldSuffix:(UITextField*)textField withString:(NSString*)string
{
    BOOL returnUpdateSuffix = NO;
    if (string != nil && [string respondsToSelector:@selector(length)] && [string length] > 0)
    {
        NSObject *labelSuffix = textField.rightView;
        if (labelSuffix != nil && [labelSuffix respondsToSelector:@selector(setText:)])
        {
            [(UILabel*)labelSuffix setTextAlignment:NSTextAlignmentRight];
            [(UILabel*)labelSuffix setText:string];
            [(UILabel*)labelSuffix setBackgroundColor:[UIColor redColor]];
            {
                NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                      ((UILabel*)labelSuffix).font, NSFontAttributeName,nil];
                CGRect frame = [((UILabel*)labelSuffix).text boundingRectWithSize:CGSizeMake(0.0f, CGFLOAT_MAX)
                                                                          options:NSStringDrawingUsesLineFragmentOrigin
                                                                       attributes:attributesDictionary
                                                                          context:nil];
                CGSize size = frame.size;
                CGRect newFrame = [(UILabel*)labelSuffix frame];
                newFrame.size.width = size.width;
                [(UILabel*)labelSuffix setFrame:newFrame];
                [(UILabel*)labelSuffix setNeedsLayout];
                [(UILabel*)labelSuffix layoutIfNeeded];
            }            
            returnUpdateSuffix = YES;
        }
    }    
    return returnUpdateSuffix;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接