简体   繁体   中英

How to limit character input in UIAlertView UITextField

I am trying to limit the number of characters my user is allowed to input into my UITextField within my UIAlertView .

I've tried the some common answers on the web. Such as shown below :

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

Anyone able to help?

.h file

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

Unfortunately this isn't allowed. You aren't allowed to mess with a UIAlertView s hierarchy and so you can't go changing things on it like the UITextField s properties.

Please see this link

Specifically

The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified

EDIT

Whilst you shouldn't be messing with the UIAlertView hierarchy itself like I have said above, you might actually be able to set the UITextField s delegate but first you need to retrieve it. First make sure you have set the UITextFieldDelegate in the header file ( .h file).

Then after you have created your UIAlertView and set the alertViewStyle: property , so we have something like

// 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];

Once we have set the delegate you should then enter your method as shouldChangeCharactersInRange: is a UITextFieldDelegate method.

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

Warning

As the text field being retrieved from textFieldAtIndex: is part of the UIAlertView s hierarchy Apple may class this as altering the UIAlertView which isn't allowed (See first part of answer) and whatever you do don't use addSubview: when using UIAlertView s

Try with this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM