【发布时间】:2012-02-09 06:25:00
【问题描述】:
我正在开发一个 iphone 应用程序,只要在文本字段中键入一个字符,我就必须返回键盘。如何实现这一点,请提出一些解决方案。
谢谢。
【问题讨论】:
标签: iphone objective-c xcode ipad uitextfield
我正在开发一个 iphone 应用程序,只要在文本字段中键入一个字符,我就必须返回键盘。如何实现这一点,请提出一些解决方案。
谢谢。
【问题讨论】:
标签: iphone objective-c xcode ipad uitextfield
第 1 步:创建一个实现 UITextFieldDelegate 协议的类
@interface TheDelegateClass : NSObject <UITextFieldDelegate>
第 2 步:在您的实现中,覆盖方法 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// newString is what the user is trying to input.
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([newString length] < 1) {
// If newString is blank we will just ingore it.
return YES;
} else
{
// Otherwise we cut the length of newString to 1 (if needed) and set it to the textField.
textField.text = [newString length] > 1 ? [newString substringToIndex:1] : newString;
// And make the keyboard disappear.
[textField resignFirstResponder];
// Return NO to not change text again as we've already changed it.
return NO;
}
}
第 3 步:将委托类的一个实例设置为 UITextField 的委托。
TheDelegateClass *theDelegate = [[TheDelegateClass alloc] init];
[theTextField setDelegate:theDelegate];
【讨论】:
您必须在文本委托方法中编写代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([textField.text length] == 1){
[textField resignFirstResponder];
}
然后检查textFieldDidBeginEditing中的字符串长度
- (void)textFieldDidBeginEditing:(UITextField *)textField{
if([textField.text length] == 1){
[textField resignFirstResponder];
}
}
【讨论】:
在 textField 创建代码中添加通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText:) name:UITextFieldTextDidChangeNotification object:textField];
并实施
- (void) changeText: (id) sender;
{
if ([textField.text length] == 1)
{
[textField resignFirstResponder];
}
}
【讨论】:
我猜这就是你要找的东西?
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[add your method here];
return YES;
}
或者,如果您希望它在开始编辑时立即辞职,您可以将此代码放入 textFieldDidBeginEditing: 委托方法
[textField resignFirstResponder];
查看此链接
【讨论】:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([textField.text length] == 1){
[textField resignFirstResponder];
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if([textField.text length]==1)
{
// here perform the action you want to do
}
}
【讨论】: