如何在 UIAlertView UITextField 中限制字符输入 [英] How to limit character input in UIAlertView UITextField
本文介绍了如何在 UIAlertView UITextField 中限制字符输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图限制我的用户可以在我的 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;
}
有人可以帮忙吗?
推荐答案
.h 文件
@property (strong,nonatomic) UITextField *alertText;
@interface LocationSearchViewController : UIViewController<UITextFieldDelegate>
.m 文件
- (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;
}
迅捷
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
}
这篇关于如何在 UIAlertView UITextField 中限制字符输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文