我有UIAlertView
的子类,在其中我显示了一个接受输入的textField
。当用户点击textField
时,键盘出现,UIAlertView
向上移动以调整键盘。但当我在UIAlertView
的didPresentAlertView
委托方法中执行[textField becomeFirstResponder]
时,alertView不会向上移动以调整键盘。相反,UIAlertView
被隐藏在键盘后面。
PS-我知道苹果公司说UIAlertView
不应该被子类化并按原样使用,但我之所以将UIAlertView
子类化,是因为我想重新设计苹果公司在其中的默认UI元素
你真的不应该违背苹果的建议。
原因
- 你可能会遇到意想不到的问题,比如你所面临的问题
- 您的代码可能会在未来的iOS版本中中断,因为您违反了建议
- 重新设计苹果的标准控件违反了HIG的指导方针。因此,您的应用程序可能会被拒绝。使用
UIView
子类创建自己的子类
作为替代方案,苹果公司在UIAlertView
中对此要求做出了规定。您不需要在警报视图中添加文本字段,而是使用UIAlertView
属性alertViewStyle
。它接受枚举UIAlertViewStyle
中定义的值
typedef NS_ENUM(NSInteger, UIAlertViewStyle) {
UIAlertViewStyleDefault = 0,
UIAlertViewStyleSecureTextInput, // Secure text input
UIAlertViewStylePlainTextInput, // Plain text input
UIAlertViewStyleLoginAndPasswordInput // Two text fields, one for username and other for password
};
例如,让我们假设一个用例,您希望接受用户的密码。实现这一点的代码如下。
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please enter password"
message:nil
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Continue", nil];
[alert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
[alert show];
为了验证输入,比如说输入的密码必须至少有6个字符,实现这个委托方法,
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] >= 6 )
{
return YES;
}
else
{
return NO;
}
}
获取用户输入
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"Login"])
{
UITextField *password = [alertView textFieldAtIndex:0];
NSLog(@"Password: %@", password.text);
}
}
为了重新迭代,UIAlertView
具有私有视图层次结构,建议在不进行修改的情况下按原样使用。如果你违背建议使用它,你会得到意想不到的结果。
来自苹果文档
UIAlertView类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不能修改。
这是即使在iOS默认应用程序中也使用的标准技术(例如:输入Wi-Fi密码等),因此使用此技术将确保您不会面临您提到的问题。
希望能有所帮助!
我确实喜欢这样来提升屏幕以显示文本文件。:-)希望这对你有所帮助。
- (void) textFieldDidBeginEditing:(UITextField *)textField {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[UIView setAnimationBeginsFromCurrentState:YES];
self.view.frame = CGRectMake(( self.view.frame.origin.x), (self.view.frame.origin.y-50 ), self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
- (void) textFieldDidEndEditing:(UITextField *)textField {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[UIView setAnimationBeginsFromCurrentState:YES];
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+50 , self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}