ios - UITextView 上边距

标签 ios uitextview uikeyboard

我使用的是 textview,我注意到 iOS 7 默认留有上边距。见下图enter image description here

我阅读了不同的帖子,其中最常用的解决方案是:

[textViewTest setContentInset:UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)];

但这些插图只是针对特定设备、 TextView 、字体大小等的自定义解决方案。因此,没有适用于任何解决方案的特定插图......甚至最糟糕的是,我将不得不以编程方式定义不同的插图以说明所有 iOS 设备和方向。

好消息是,我发现每当 textview 成为第一响应者并且键盘显示在屏幕上时,即使键盘消失,这个上边距也会消失。顺便说一句,我正在调整 UIKeyboardDidShowNotification 和 UIKeyboardWillHideNotification 上的 contentInset 的大小。

  • 在键盘显示时查看图像:

enter image description here

  • 键盘消失后查看图像:

enter image description here

有没有办法模拟键盘显示和隐藏?这样内容插入就会消失,如上文所述。

我已经尝试让 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/

相关文章:

iphone - 防止 sqlite 转义反斜杠

iphone - iPhone 是否有相当于 NSTokenField 控件?

iphone - 用于检测电话号码和超链接的 UITextView 设置

objective-c - 显示键盘时无法与 ScrollView 中的(某些)UI 元素交互

iphone - 如何解决使用未声明的标识符 'UIKeyboard' 错误?

ios - Swift:在 UITableViewCell 的 UITextView 中插入复选框并使用 UITapGestureRecognizer 识别复选框上的点击

iphone - 如何在调试期间在 iPad 中保持相同的 iPhone 应用尺寸

ios - 将纹理图集拆分为多个纹理图集警告

objective-c - 查看过渡动画

ios - XCode 应用程序图标错误