gpt4 book ai didi

ios - 在 iOS Objective-c 中粘在键盘上的自定义 UIView

转载 作者:行者123 更新时间:2023-12-01 20:00:56 24 4
gpt4 key购买 nike

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

5年前关闭。




Improve this question




我想制作一个粘在键盘上的自定义 UIView,我使用了输入附件 View ,但是当键盘离开时它不会留在我的 View Controller 上。在 iOS Objective-C 中,如何让我限制在 View Controller 底部的 UIView 粘在键盘上(如输入附件 View )?

最佳答案

为 View 的底部约束添加一个 IBOutlet。我假设它是 ViewController View 的直接 subview ,当键盘隐藏时它应该位于底部。

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

在 viewWillAppear 中订阅键盘通知:
NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(hideKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)

在 viewDidDisappear 中取消订阅:
NotificationCenter.default.removeObserver(self)

稍后在您的 ViewController 中:
@objc func showKeyboard(_ notification: NSNotification) {
let info = notification.userInfo
let rectValue = info![UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
if let keyboardSize = rectValue?.cgRectValue.size {
bottomConstraint.constant = keyboardSize.height
view.layoutIfNeeded()
}
}

@objc func hideKeyboard(_ notification: Notification) {
bottomConstraint.constant = 0
view.layoutIfNeeded()
}

objective-C :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)keyboardWillShow: (NSNotification *) notification {
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
_bottomConstraint.constant = keyboardSize.height;
[view layoutIfNeeded];
}

-(void)keyboardWillHide: (NSNotification *) notification {
_bottomConstraint.constant = 0;
[view layoutIfNeeded];
}

关于ios - 在 iOS Objective-c 中粘在键盘上的自定义 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39924238/

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