天天看點

限制UIAlertView上的TextField的輸入字元長度

一個漢字占兩個字元長度

 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"簽名" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

   alertView.alertViewStyle = UIAlertViewStylePlainTextInput;  //設定AertView的樣式,帶有一個輸入框

    alertView.delegate = self;

    [[alertView textFieldAtIndex:0] addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];  //給alertView的textField添加一個事件 因為TextField沒有didChange方法

//alertView的textField的響應事件

- (void)textFieldDidChange:(UITextField *)textField

{

    if (textField.markedTextRange == nil) { //輸入中文時,當英文轉為中文後再調用convertToInt::事件

        textField.text = [self convertToInt:textField.text :64];

    }

}

- (NSString *)convertToInt:(NSString *)text :(int)length

{

    int i, n = [text length], l = 0, a = 0, b = 0;

    int len = 0;

    unichar c;

    for (i = 0; i < n; i++) {

        c = [text characterAtIndex:i];

        if (isblank(c)) { // 判斷輸入的字元是否為空格或者換行

            b++;

        } else if (isascii(c)) { // 判斷輸入的字元是否為英文

            a++;

        } else { // 判斷輸入的字元是否為中文

            l++;

        }

        len = l * 2 + (int)ceilf((float) (a + b)); // ceilf去最接近的較大整數

        if (len > length) {

         [[UIApplication sharedApplication].keyWindow makeToast:[NSString stringWithFormat:@"最多隻允許輸入%d個英文字元,漢字占兩個字元", length] duration:defaultDuration position:@"center"];  

            return [text substringToIndex:i];

        }

    }

    if (a == 0 && l == 0) {

        return text;

    }

    return text;

}