【发布时间】:2014-03-02 21:54:56
【问题描述】:
我正在使用 textview 并注意到 iOS 7 默认情况下会留下上边距。见下图
我阅读了不同的帖子,其中最常见的解决方案是使用:
[textViewTest setContentInset:UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)];
但这些插图只是针对特定设备、文本视图、字体大小等的自定义解决方案。因此,没有适用于任何解决方案的特定插图……更糟糕的是,我必须以编程方式定义不同的插图来考虑所有 iOS 设备和方向。
好消息是,我发现每当 textview 成为第一响应者并且键盘显示在屏幕上时,即使在键盘消失后,该上边距也会消失。顺便说一句,我正在调整 UIKeyboardDidShowNotification 和 UIKeyboardWillHideNotification 上 contentInset 的大小。
- 当键盘显示时查看图像:
- 键盘消失后查看图像:
有没有办法模拟键盘显示和隐藏?这样内容插图就会消失,如上所述。
我已经尝试让 textview 成为第一响应者,然后将其退出,但是对于这种方法,用户必须看到整个键盘的显示-隐藏动画。
提前致谢!
我的代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
if(self.topMarginIsAlreadyResized == NO) {
[self.myTextView becomeFirstResponder]; // Keyboard will show to eliminate top margin when view appears
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)handleKeyboardDidShow:(NSNotification *)notification {
if(self.topMarginIsAlreadyResized == NO) {
self.topMarginIsAlreadyResized = YES; // Once that keyboard has shown when view appears, we should hide it manually
[self.myTextView resignFirstResponder];
}
NSValue *keyboardRectAsObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = CGRectZero;
[keyboardRectAsObject getValue:&keyboardRect];
self.myTextView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, keyboardRect.size.height, 0.0f);
}
- (void)handleKeyboardWillHide:(NSNotification *)notification {
self.myTextView.contentInset = UIEdgeInsetsZero;
}
【问题讨论】:
-
为什么您认为您需要为每个设备和方向配备一套新的边缘插件...?
-
您可以在 handleKeyboardDidShow 方法中辞职第一响应者。它会显示你的键盘动画。
-
我想要实现的是在加载视图控制器时消除上边距。有任何想法吗?我知道我可以通过使用 setContentInset(仅提供估计)以及显示键盘并在考虑键盘时自动计算 setContentInset 来实现它。
标签: ios uitextview uikeyboard