ios - 键盘出现时移动视图
问题描述
在屏幕上,我有几个要注册的测试字段。为了使键盘不与字段重叠,我更改了约束。但有一个问题。这些字段出现在不需要的大屏幕上。我怎样才能摆脱它并在真正需要时更改约束。
ViewController.swift
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@objc func keyboardWillShow(notification: NSNotification) {
var keyboardHeight = CGFloat(0.0)
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
keyboardHeight = keyboardRectangle.height
}
UIView.animate(withDuration: 3) {
self.viewBottomConstraint.constant = keyboardHeight + 5
self.topIconConstraint.constant = 40
self.view.layoutIfNeeded()
}
}
@objc func keyboardWillHide() {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1) {
self.viewBottomConstraint.constant = 250
self.topIconConstraint.constant = 150
self.view.layoutIfNeeded()
}
}
解决方案
推荐阅读
- html - 背景附件:固定,在 Chrome 版本之间移动位置
- java - 在指定位置放置文本(数字)
- airflow - 在长时间运行的作业期间重新启动时,气流调度程序最终卡住
- c# - 将数据表转换为列表
- vbscript - 无法在 ASP Classic 中设置命令对象属性
- java - 具有 DatatypeFactory 的神奇 00:09 时区
- google-sheets - Google 电子表格 - 使用选项卡名称作为公式中的参考
- php - 找到准确和相似的名称并返回一个带有 preg_match 的数组
- python - 使用 Selenium/Chrome 和 Python 下载多个 csv 文件
- autopep8 - 是否可以自定义 autopep8 格式?