gpt4 book ai didi

ios - 带有 keyboardWillShow 的 UITableView 和 UIView

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:30 25 4
gpt4 key购买 nike

我有一个 UITableView,它几乎填满了我的整个 UIViewController,我在底部有一个 UIView,其中包含一个按钮和一个文本字段。

当我点击文本字段时,我希望 UIView 和 tableview 向上推,这样 UIView 就在键盘的顶部。

- UIView:  
- UITextField
- UIButton

我在这里尝试了多种建议,但似乎没有一种适合我的情况。

最佳答案

第一步:
制作UIView

底部约束的outlet

enter image description here

第 2 步:
添加键盘显示和隐藏的观察者,然后根据键盘高度更改约束常量..

//**In viewDidLoad method** 

// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];

Swift 5 中的第 2 步:

//**In viewDidLoad method** 

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

第 3 步:
在键盘显示和隐藏通知时管理约束,如下所示

- (void)keyboardWillShow:(NSNotification *)notification
{

NSDictionary* userInfo = [notification userInfo];

// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

CGSize keyboardSizeNew = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

_bottomConstraintofView.constant = keyboardSizeNew.height;

[UIView animateWithDuration:0.2
animations:^{
[self.view layoutIfNeeded]; // Called on parent view
}];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
_bottomConstraintofView.constant = 0;
[UIView animateWithDuration:0.2
animations:^{
[self.view layoutIfNeeded];
}];
}

Swift 中的解决方案

func keyboardWillShow(notification: NSNotification){
let userInfo:NSDictionary = notification.userInfo!
let keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size

let keyboardSizeNow:CGSize = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue().size

self.bottomConstraintofView.constant = keyboardSizeNow.height
UIView.animateWithDuration(0.2) {
self.view.layoutIfNeeded()
}
}

func keyboardWillHide(notification: NSNotification){
bottomConstraintofView.constant = 0
UIView.animateWithDuration(0.2) {
self.view.layoutIfNeeded()
}
}

关于ios - 带有 keyboardWillShow 的 UITableView 和 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com