我使用的是 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;
}
最佳答案
发生这种情况是因为您的 View Controller 已将属性 automaticallyAdjustsScrollViewInsets
设置为 YES,如果将其设置为 NO,一切都会好起来的。看这个question以及接受的答案以获取更多信息。
关于ios - UITextView 上边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594684/