ios - UITableView 以编程方式未显示

标签 ios swift uitableview

我使用以下代码以编程方式创建表格 View :

lazy var myTableView: UITableView =
{
    let tableView = UITableView()
    tableView.delegate = self
    tableView.dataSource = self
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    return tableView
}()

然后我将其作为 subview 添加到 viewDidLoad 中的 View 中:

view.addSubview(myTableView)

然后在我设置所有 UI 约束的方法中,我将其布局如下:

myTableView.widthAnchor.constraintEqualToAnchor(view.widthAnchor).active = true
myTableView.topAnchor.constraintEqualToAnchor(temporaryContainerView.bottomAnchor).active = true

最后,这是我的委托(delegate)/数据源方法:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
    cell.textLabel?.text = "Test"

    return cell
}

当我在上述方法上放置断点时,似乎 numberOfRowsinSection 被调用了很多次,但 cellForRowAtIndexPath 根本没有被调用。

为什么没有出现?

最佳答案

我必须在我的 TableView 上设置 centerXAnchor 约束,以便它能够正确定位以及 TranslatesAutoresizingMaskIntoConstraints = false

关于ios - UITableView 以编程方式未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863284/

相关文章:

ios - 无法在 Firebase 中获取节点的值

ios - AVAudioPlayer 不从网站播放 m4a 或 mp3 文件类型

ios - Clevertap 推送通知声音问题

ios - 如何将具有多个 segues 的 Storyboards 用于一个 View Controller ?

ios - 日期格式化程序不从应用程序中的字符串返回日期,但可以在 Playground 上工作

ios - iOS 13 和 iPhone 11 Pro 模拟器下的 tableView.rowHeight = UITableView.automaticDimension 导致无限更新 subview 循环

ios - dequeueReusableCell() 与 UITableViewCell()

iphone - 如何将值传递给另一个 View Controller ?

iphone - dismissViewControllerAnimated :completion: has a couple second delay

objective-c - 从 NSData 转换的 NSString 中删除 unicode 和反斜杠转义