Я бы хотел увеличить высоту таблицы при исчезновении клавиатуры.У меня есть табличное представление, которое заполняется снизу вверх.Табличное представление не полностью заполнено данными, означая, что есть некоторое пустое место наверху табличного представления.Там будет несколько ячеек в табличном виде.Поскольку табличное представление заполняется снизу вверх, эти ячейки должны располагаться к нижней части табличного представления.Когда отображается клавиатура, общая высота таблицы составляет около половины экрана.Когда клавиатура исчезает, общая высота таблицы должна составлять почти весь экран.Это означает, что когда клавиатура исчезает, ячейки должны начинаться с экрана.
Вот как это выглядит, когда в табличном представлении есть две ячейки:
Вот как это выглядит, когда двав таблицу добавлено больше ячеек:
![enter image description here](https://i.stack.imgur.com/6eUpL.png)
Вот как это выглядит при исчезновении клавиатуры:
![enter image description here](https://i.stack.imgur.com/f9A4o.png)
Когда клавиатура исчезает, четыре ячейки должны начинаться с нижней части экрана, а не с половины экрана.Четыре ячейки должны сместиться вниз, чтобы они начинались там, где находится серая линия внизу экрана.Не должно быть большого промежутка между тем, где находится первая ячейка (на которой написано «Apple»), и где находится серая линия внизу экрана.В то же время сам 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
}
}
Я попытался добавить следующий код к моей функции клавиатурыWillShow:
var tableViewFrame: CGRect!
tableViewFrame = self.tableView.frame
tableViewFrame.size.height += 146.0
tableView.frame = tableViewFrame
tableView.contentInset = UIEdgeInsetsMake(146.0, 0, 0, 0);
Однако, когда клавиатураисчезают, на экране появляются горизонтальные серые линии, как показано ниже:
РЕДАКТИРОВАТЬ:
![enter image description here](https://i.stack.imgur.com/OdVuy.png)
Эти горизонтальные серые линии (всего шесть) не должны быть там.Как я могу предотвратить их появление после исчезновения клавиатуры?