在项目中,我遇到了这个问题。
其中一个控制器实现了
问题出在这里,在关闭
以下是我遇到问题的代码。
其中一个控制器实现了
keyboardWillShow
和keyboardWillHide
(来自苹果官方的标准代码管理键盘)。
在背景点击时,UIAlertView
出现(基于某些验证),UIAlertView
只有一个按钮,用于简单关闭UIAlertView
。问题出在这里,在关闭
UIAlertView
时,keyboardWillShow
和keyboardWillHide
再次被调用。以下是我遇到问题的代码。
#import "ViewController.h"
@interface ViewController () <UITextFieldDelegate>
{
int timeCalledShow;
int timeCalledHide;
}
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
- (IBAction)backgroundTapped:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardDidHideNotification
object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification {
timeCalledShow+=1;
NSLog(@"show Time Called %d", timeCalledShow);
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets;
if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0);
} else {
contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.width), 0.0);
}
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)keyboardWillHide:(NSNotification *)notification {
timeCalledHide+=1;
NSLog(@"Hide Time Called %d", timeCalledShow);
self.scrollView.contentInset = UIEdgeInsetsZero;
self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)backgroundTapped:(id)sender {
[[[UIAlertView alloc] initWithTitle:@"Testing" message:@"Keyboard hide & show, due to alert view" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] show];
[self.view endEditing:YES];
}
@end
注意事项
- 我已经查看了keyboardWillShow called twice和类似的问题,但没有找到答案。
- 它在上运行良好。
- 这是测试代码的链接。
编辑
我已经知道了解决方法的代码。但真正的问题是,如何使UIAlertView
触发keyboardWillShow
通知。
编辑代码 我已经尝试过@Chonch建议的以下代码,但使用此代码后键盘永远不会关闭。也就是说,在关闭警报后键盘再次出现。
- (IBAction)backgroundTapped:(id)sender {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"testing" message:@"Keyboard" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[self.textField resignFirstResponder];
}