所以我有这个UITextField
我想显示 UITableView
就在它下面。我试图在 UITableView
中显示建议我的逻辑工作正常,但我想知道如何显示 UITableView
在 UITextField
下方.
目前,我正在做这样的事情
private func setUpAutoCompleteTable() {
autocompleteTableView = UITableView(frame: CGRect(x: self.originTextField.bounds.minX,y: self.originTextField.bounds.maxY,width: self.originTextField.bounds.width,height: self.originTextField.bounds.height * 4), style: UITableView.Style.plain)
self.view.addSubview(autocompleteTableView)
autocompleteTableView.delegate = self
autocompleteTableView.dataSource = self
autocompleteTableView.isScrollEnabled = true
autocompleteTableView.isHidden = true
autocompleteTableView.register(LocationAutoCompleteCell.self, forCellReuseIdentifier: "AutoCompleteRowIdentifier")
}
但它在屏幕顶部显示表格。我想告诉你originTextField
在另一个 View 内。更新
这就是 View 层次结构的外观。
最佳答案
因此,要以编程方式布局 tableView,您需要在 ViewController 中声明它
var autoCompleteTableView: UITableView!
在 ViewDidLoad 中初始化
autoCompleteTableView = UITableView(frame: .zero) // constraints will set the frame for us later
在 ViewDidLoad 中设置约束
NSLayoutConstraint.activate([
autoCompleteTableView.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 5), //the constant is how many pts below the textField you want the tableView to be
autoCompleteTableView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
autoCompleteTableView.widthAnchor.constraint(equalTo: view.widthAnchor),
autoCompleteTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
然后你可以设置你需要的任何 tableView 属性。记住,你的 VC 也需要实现
UITableViewDelegate
和 UITableViewDataSource
关于ios - 如何以编程方式使用 swift 在 UITextField 下方显示 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60120488/