我正在使用textview并注意到默认情况下iOS 7会留下一个上边距。请参阅以下
中的图片我阅读了最常用解决方案的不同帖子:
[textViewTest setContentInset:UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)];
但是这些插件只是特定设备,textview,字体大小等的自定义解决方案。因此,没有适用于任何解决方案的特定插图......即使最糟糕的是,我还必须以编程方式定义不同的插图以适应所有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;
}
答案 0 :(得分:26)
这是因为您的视图控制器已将属性automaticallyAdjustsScrollViewInsets
设置为YES,如果将其设置为NO,则一切都会正常。有关详细信息,请参阅此question和接受的答案。