UITextView上边距

Ang*_*han 7 uitextview uikeyboard ios

我正在使用textview并注意到默认情况下iOS 7会留下一个上边距.请参阅以下图像在此输入图像描述

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

[textViewTest setContentInset:UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)];
Run Code Online (Sandbox Code Playgroud)

但这些插入只是特定设备,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;
}
Run Code Online (Sandbox Code Playgroud)

And*_*rea 26

发生这种情况是因为yor视图控制器已将该属性设置automaticallyAdjustsScrollViewInsets为YES,如果将其设置为NO,则一切都会正常.有关详细信息,请参阅此问题和接受的答案.