如何在UIAlertView的UITextField中限制字符输入

3

我正在尝试限制用户在UIAlertView中输入的字符数。我尝试了网上一些常见的解决方案,例如下面所示:

  #define MAXLENGTH 10


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH) {
        textField.text = [textField.text substringToIndex:MAXLENGTH-1];
        return NO;
    }
    return YES;
}

有人能帮忙吗?


很遗憾,我认为这是不允许的 - 参考 https://developer.apple.com/library/ios/documentation/uikit/reference/UIAlertView_Class/UIAlertView/UIAlertView.html “UIAlertView类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不得修改”。 - Popeye
你是否正在使用textfielddelegate? - Watsche
3个回答

8

.h 文件

  @property (strong,nonatomic)  UITextField *alertText;

@interface LocationSearchViewController : UIViewController<UITextFieldDelegate>

.m file

- (IBAction)butPostalCode:(id)sender {

UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alrt.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alrt textFieldAtIndex:0] setPlaceholder:@"Enter postal Code"];
alertText = [alrt textFieldAtIndex:0];
alertText.keyboardType = UIKeyboardTypeNumberPad;
alertText.delegate=self;
alrt.tag=100;
[alrt show];
}



-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(yourtextfieldname.text.length >= 10 && range.length == 0) {
    return NO;

}
return YES;
}

Swift

class LocationSearchViewController: UIViewController, UITextFieldDelegate {

 Var alertText:UITextField!
}

func butPostalCode(sender: AnyObject) {
var alrt: UIAlertView = UIAlertView(title: "", message: "", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alrt.alertViewStyle = .PlainTextInput
alrt.textFieldAtIndex(0).placeholder = "Enter postal Code"
alertText = alrt.textFieldAtIndex(0)
alertText.keyboardType = .NumberPad
alertText.delegate = self
alrt.tag = 100
alrt.show()
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if yourtextfieldname.text.length >= 10 && range.length == 0 {
    return false
}
return true
}

1

很不幸,这是不允许的。您不能干涉 UIAlertView 的层次结构,因此无法更改像 UITextField 的属性之类的东西。

请参见link

具体来说:

UIAlertView 类旨在按原样使用,并且不支持子类化。此类的视图层次结构是私有的,不得修改

编辑

虽然您不应该像上面所说的那样操纵 UIAlertView 层次结构本身,但实际上您可能可以设置 UITextField 的委托,但首先需要检索它。首先确保您已在头文件(.h 文件)中设置了 UITextFieldDelegate

接着,在创建了UIAlertView并设置了alertViewStyle:属性之后,我们会得到如下代码:

// We create an instance of our UIAlertView
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"My Alert"
                                                  message:nil
                                                 delegate:self
                                        cancelButtonTitle:@"Cancel"
                                        otherButtonTitles:@"OK", nil];

// We set the alertViewStyle to a plain text input, so 1 textfield
[myAlert setAlertViewStyle:UIAlertViewStylePlainTextInput];

// Then we retrieve that UITextField from the index 0 
UITextField *plainTextField = [myAlert textFieldAtIndex:0];
// Now that we have retrieved the text field we can set the delegate on it/
// Probably best to give it a tag as well so we can identify it later.
[plainTextField setDelegate:self]; 
[plainTextField setTag:1001];

一旦我们设置了委托,您就应该将shouldChangeCharactersInRange:方法输入为 UITextFieldDelegate方法。
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Make sure that it is our textField that we are working on otherwise forget the whole thing.
    if([textField tag] == 1001) {
        if([textField text].length >= 10 && range.length == 0) {
            return NO;
        }
    }
    return YES;
}

警告

由于从textFieldAtIndex:检索的文本字段是UIAlertView层次结构的一部分,因此苹果公司可能会将其归类为更改UIAlertView,而这是不允许的(请参见答案的第一部分)。无论您做什么,都不要在使用UIAlertView时使用addSubview:


@rosshump 请注意,自从我写这篇文章以来,文档已经发生了变化。虽然我所说的依然成立,但是UIAlertView的层次结构修改的文档资料较少,因为该类已被弃用。 - Popeye
哦,好的,谢谢你告诉我!我还没有为iOS 8更新我的应用程序,但我会确保阅读文档并相应地更新它们。谢谢 :) - rosshump

0

试试这个:

#define MAXLENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *nextValue = [NSString stringWithFormat:@"%@%@", textField.text, string];
    if ([nextValue length] > MAXLENGTH) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Attention"
                                              message:@"You can't insert more than 10 characters"                          
                                              delegate:nil cancelButtonTitle:nil                          
                                              otherButtonTitles:@"Close", nil];        
        [alert show];            
        return NO;            
    }
    return YES;
}

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