ios - 如何以编程方式使用 swift 在 UITextField 下方显示 UITableView?

标签 ios swift uitableview

所以我有这个UITextField我想显示 UITableView就在它下面。我试图在 UITableView 中显示建议我的逻辑工作正常,但我想知道如何显示 UITableViewUITextField 下方.
目前,我正在做这样的事情

 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 也需要实现 UITableViewDelegateUITableViewDataSource

关于ios - 如何以编程方式使用 swift 在 UITextField 下方显示 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60120488/

相关文章:

javascript - 如何将包含 JSON 的 JSON NSString 从 Objective C 方法传递给 Javascript 方法

swift - 无法从 View Controller 转到 Storyboard 引用?

swift - XCode9.4.1 swift : Showing image instead of text on map annotations

ios - Swift iOS - 当作为 subview Controller 添加到另一个 View Controller 时,是否应该在 subview Controller 中调用 Deinit?

ios - 如何在 Xcode 中创建具有多列的 UI TableView?

Swift:从 Firebase 数据库检索数据以进行标签

iphone - UITableViewCell 上的 UIPopoverController

ios - 将回调添加到预构建的异步函数 Swift iOS

ios - 如何修复 swift 4 中的 UITableView 单元格重复

ios - IOS中的paypal sdk Touch id认证