【发布时间】:2019-03-29 00:14:01
【问题描述】:
我正在开发一个具有聊天功能的应用程序,所以我的要求是在键盘顶部显示文本字段。由于需要不使用滚动视图,我在 UIView 上获取了一个文本字段,并且我正在使用键盘通知(UIKeyboardWillChangeFrameNotification 和 UIKeyboardWillHideNotification)相应地滚动文本字段。
当“预测文本”打开并且用户按下听写按钮时,我面临 iPhone x 设备的问题,因为听写不需要“预测文本”,所以文本字段和键盘之间会有间隙。
我正在尝试通过 UIKeyboardWillChangeFrameNotification 检测键盘高度,但在按下听写按钮时它不会触发。
在下面添加我的示例代码。
@interface ViewController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraints;
@property (weak, nonatomic) IBOutlet UITextField *chatTextField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keywindowResign:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
}
- (void)keyboardFrameChange:(NSNotification *)notification
{
NSDictionary * userInfo = [notification userInfo];
CGRect keyboardRect = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Anchor the bottom of the message view to the top of the keyboard.
[UIView animateWithDuration:duration animations:^{
self.bottomConstraints.constant = 0 - CGRectGetHeight(keyboardRect) + self.view.safeAreaInsets.bottom;
[self.view layoutIfNeeded];
}];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
NSDictionary * userInfo = [notification userInfo];
double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Anchor the bottom of the message view to the bottom of the screen.
[UIView animateWithDuration:duration animations:^{
self.bottomConstraints.constant = 0;
[self.view layoutIfNeeded];
}];
}
- (void)keywindowResign:(NSNotification *)notification
{
NSLog(@"%s","Key window resign");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:true];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
请查看屏幕截图以了解更多信息。
【问题讨论】:
标签: ios objective-c keyboard speech-to-text iphone-x