我在应用程序的 TextView 上使用以下代码。我已经做到了,当键盘触发时, View 将上升到键盘顶部,当我单击键盘和 TextView 之外时,它将关闭键盘。我遇到的问题是,当我单击 TextView 时, TextView 在键盘顶部移动大约 5 秒,然后弹出,而且当我单击关闭键盘时,它会立即消失并且不会像动画一样键盘确实打开了。有什么方法可以解决这个问题,并使 View 在键盘打开和关闭时在键盘顶部移动而不是跳跃?
谢谢
- (void)viewDidLoad
{
[super viewDidLoad];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(didShow:) name:UIKeyboardDidShowNotification object:nil];
[center addObserver:self selector:@selector(didHide) name:UIKeyboardWillHideNotification object:nil];
_theTextView.delegate = self;
_theTextView.text = @"Type your message..";
_theTextView.textColor = [UIColor lightGrayColor]; //optional
_theTextView.layer.cornerRadius = 5;
_theTextView.layer.masksToBounds = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
-(void)dismissKeyboard {
[_theTextView resignFirstResponder];
}
- (void)didShow:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
self.textViewPOS.constant = keyboardSize.height;
NSLog(@"Opened");
}
- (void)didHide
{
self.textViewPOS.constant = 0;
NSLog(@"Closed");
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSLog(@"typing");
return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@"Type your message.."]) {
textView.text = @"";
textView.textColor = [UIColor blackColor]; //optional
}
[textView becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
if ([textView.text isEqualToString:@""]) {
textView.text = @"Type your message..";
textView.textColor = [UIColor lightGrayColor]; //optional
}
[textView resignFirstResponder];
}
@end
最佳答案
对于延迟问题,您可以按照 Eugene Zaychenko 的建议使用 UIKeyboardWillShowNotification
。它会解决你的问题。
[center addObserver:self selector:@selector(willShow:) name:UIKeyboardWillShowNotification object:nil];
对于动画,请使用以下代码
- (void)didHide
{
self.textViewPOS.constant = 0;
NSLog(@"Closed");
[UIView animateWithDuration:1 delay:0 options:0 animations:^{
self.textViewPOS.constant = 0;
[self.view layoutIfNeeded];
} completion:nil];
}
- (void)willShow:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
[UIView animateWithDuration:1 delay:0 options:0 animations:^{
self.textViewPOS.constant = keyboardSize.height;
[self.view layoutIfNeeded];
} completion:nil];
NSLog(@"Opened");
}
如果有任何疑问,请告诉我。
关于ios - Objective C View 不随键盘移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278942/