ios - 键盘消失时增加Tableview的高度?
问题描述
每当键盘消失时,我想增加表格视图的高度。我有一个从底部向上填充的表格视图。tableview 没有完全填充数据,这意味着 tableview 顶部有一些空白空间。表格视图中会有一些单元格。由于表格视图是从底部向上填充的,因此这些单元格应该朝向表格视图的底部。当显示键盘时,tableview 的总高度大约是屏幕的一半。当键盘消失时,tableview 的总高度应该几乎是整个屏幕。这意味着当键盘消失时,单元格应从屏幕下方开始。
这是当 tableview 中有两个单元格时的样子:
这是向 tableview 添加另外两个单元格时的样子:
这是键盘消失时的样子:
当键盘消失时,四个单元格应该从屏幕底部开始,而不是从屏幕中间开始。四个单元格应该向下移动,以便它们从屏幕底部的灰线开始。第一个单元格(显示“Apple”)的位置与屏幕底部的灰线位置之间不应有很大的差距。同时,tableView 本身应该更大。这意味着虽然 tableview 的顶部保持在同一个位置,但 tableview 的底部现在比以前低了,因为键盘现在没有占据大约一半的屏幕。我怎样才能做到这一点?谢谢。
这是我现在的代码:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var lowerGrayLine: UIView!
@IBOutlet weak var tableView: UITableView!
var fruits = [FruitModel]()
override func viewDidLoad() {
super.viewDidLoad()
//Adjust height of the lower Gray Line
lowerGrayLine.frame.origin.y = 411
//No dividing lines in the tableview initially
self.tableView.separatorStyle = .none
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
if (self.tableView(self.tableView, numberOfRowsInSection: 0) > 0)
{
self.updateTableContentInset()
}
// Allow for keyboard dismissal
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Show keyboard
textField.becomeFirstResponder()
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
//Adjust text box, and dividing line placement
textField.frame.origin.y = 416
lowerGrayLine.frame.origin.y = 411
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
textField.frame.origin.y = 597
lowerGrayLine.frame.origin.y = 557
}
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.fruits.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "fruitCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? FruitTableViewCell else {
fatalError("The dequeued cell is not an instance of FruitTableViewCell.")
}
var fruitName = fruits[indexPath.row]
var fruitNamename = fruitName.name
var colon = ":"
cell.nameLabel.text = fruitNamename + colon
cell.fruitLabel.text = fruitName.fruit
//Make some adjustments to make a line appear when a fruitCell is actually being shown
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
// This causes the bottom-most cell to not have a cell separator
if (indexPath.row == fruits.count-1) {
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
// Adjust the tableView
func updateTableContentInset() {
let numRows = tableView(tableView, numberOfRowsInSection: 0)
var contentInsetTop = tableView.bounds.size.height
for i in 0..<numRows {
contentInsetTop -= tableView(tableView, heightForRowAt: IndexPath(item: i, section: 0))
if contentInsetTop <= 0 {
contentInsetTop = 0
}
}
self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0)
self.tableView.scrollToRow(at: IndexPath(item: numRows-1, section: 0), at: .bottom, animated: false)
//Prevent scrolling
self.tableView.bounces = false;
//When we have actual fruit Cells to show, we want the line divisions
self.tableView.separatorStyle = .singleLine
}
}
我尝试将以下代码添加到我的 keyboardWillShow 函数中:
var tableViewFrame: CGRect!
tableViewFrame = self.tableView.frame
tableViewFrame.size.height += 146.0
tableView.frame = tableViewFrame
tableView.contentInset = UIEdgeInsetsMake(146.0, 0, 0, 0);
但是,当键盘消失时,屏幕上会出现水平灰线,如下图:
编辑:
这些水平灰线(共六条)不应该存在。当键盘消失时,如何防止它们出现?
解决方案
最简单的解决方案是IQKeyboardManager。这将为您管理键盘下方的空间。
否则,将底部约束添加tableViewBottomConstraint
到表视图。设置其初始值tableViewBottomConstraint.constant = 0
现在设置它等于键盘高度+填充keyboardWillShow
keyboardWillHide
func keyboardWillShow(notification: NSNotification) {
tableViewBottomConstraint.constant = keyboardHeight + padding
layoutTableView()
}
func keyboardWillHide(notification: NSNotification) {
tableViewBottomConstraint.constant = 0
layoutTableView()
}
private func layoutTableView() {
UIView.animate(withDuration: 0.3, animations: {
tableView.superview?.layoutIfNeeded()
}, completion: nil)
}
推荐阅读
- google-cloud-platform - 我知道目前在 BeamSQL 中不存在 order by 是否有任何解决方法
- sql - 如何在pgsql中将json转换为json数组
- javascript - 使用 Flask 托管模板文件时遇到问题
- node.js - 在 javaScript 中为 batchWriteItem(params,function(){}) 创建请求参数
- numpy - numpy 安装到 pypy3 虚拟环境中:`未定义的符号:cblas_sgemm`
- class - 矢量打印不正确的数据
- html - JSoup:获取维基百科页面摘要
- javascript - 在同一页面弹出窗口中显示来自另一个页面的模式内容
- vue.js - weex 输入数限制
- javascript - 映射存储在 Redux 存储中的 JSON 对象?