I have a textField on the top of my view and a tableView which should be placed below the textField.
So my code for adding them looks like:
private func setupSearchBar() {
searchtextField = UITextField()
mapView.addSubview(searchtextField)
searchtextField.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
NSLayoutConstraint(item: searchtextField, attribute: .leading, relatedBy: .equal, toItem: mapView.safeAreaLayoutGuide, attribute: .leading, multiplier: 1.0, constant: 16.0),
NSLayoutConstraint(item: searchtextField, attribute: .trailing, relatedBy: .equal, toItem: mapView.safeAreaLayoutGuide, attribute: .trailing, multiplier: 1.0, constant: -16.0),
NSLayoutConstraint(item: searchtextField, attribute: .top, relatedBy: .equal, toItem: mapView.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 24.0),
NSLayoutConstraint(item: searchtextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 46.0)
]
NSLayoutConstraint.activate(constraints)
}
after this I'm setting up my tableView:
private func setupResultsTableView() {
tableView = UITableView()
mapView.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableViewHeightAnchor = tableView.heightAnchor.constraint(equalToConstant: 0)
let constraints = [
tableView.safeAreaLayoutGuide.topAnchor.constraint(equalTo: searchtextField.safeAreaLayoutGuide.bottomAnchor),
tableView.safeAreaLayoutGuide.leadingAnchor.constraint(equalTo: mapView.safeAreaLayoutGuide.leadingAnchor),
tableView.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: mapView.trailingAnchor),
tableViewHeightAnchor!,
tableView.safeAreaLayoutGuide.bottomAnchor.constraint(lessThanOrEqualToSystemSpacingBelow: view.safeAreaLayoutGuide.bottomAnchor, multiplier: 1.0)
]
NSLayoutConstraint.activate(constraints)
}
What I want to do is: 1. To set the tableView height to 0 2. When user starts to type in my textField, according to the search results to display tablView and set its height to the contentSize of the tableView. So the maximum size will be sticked to the bottom of the device and if there are 1-2 results displayed, then to make the tableView smaller.
When user starts to type, I run the next:
func textFieldDidBeginEditing(_ textField: UITextField) {
filterContentForSearchText(textField.text!)
tableView.reloadData()
UIView.animate(withDuration: 0.6) {
self.tableView.layoutIfNeeded()
if textField.isEditing {
self.tableViewHeightAnchor.constant = self.tableView.contentSize.height
} else {
self.tableViewHeightAnchor.constant = 0.0
}
}
}
But something wrong in my code, because I get such ugly results: When I start to swipe up, the tableView starts to go up and goes over my textField
and when I finish scrolling it stops in the middle of the view
Is there a way to fix that problem? If you have any question, please ask me