【问题标题】:Programmatically added UITableView won't populate data以编程方式添加的 UITableView 不会填充数据
【发布时间】:2015-06-10 15:48:51
【问题描述】:

我希望创建UITableView 和一个自定义 单元格,并将它们添加到我的UIViewController

如果我将情节提要中的UITableView 布局到我的UIViewController 上,自定义单元格一切正常

但我意识到关于其高度的动画不是很流畅 - 有时表格视图会消失

所以我决定每次我想做一些动画时都创建/销毁一个UITableView,并将它作为子视图添加到我的UIViewController

但以编程方式添加的UITableView 不会填充数据。

我在这里做错了什么?

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var dataArr = [String]() // Holds data for UITableView
var tv: UITableView!     // Notice it's not @Outlet

override func viewDidLoad() {
    super.viewDidLoad()


    dataArr = ["one", "two", "three"]


    // Create and add UITableView as drop down
    tv = UITableView()
    tv.delegate = self
    tv.dataSource = self

    createTableView()
}

func createTableView() {
    let w = UIScreen.mainScreen().bounds.size.width
    tv.frame = CGRectMake(0, 50, w, 0)
    tv.rowHeight = 25.0

    // Register custom cell
    var nib = UINib(nibName: "searchCell", bundle: nil)
    tv.registerNib(nib, forCellReuseIdentifier: "searchCell")

    self.view.addSubview(tv)

    UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: {
            self.tv.frame.size.height = 100
        }, completion: { (didFinish) in
            self.tv.reloadData()
        })
}

func destroyTableView() {
    UIView.animateWithDuration(0.2, animations:
        {
            // Hide
            self.tv.frame.size.height = 0
        }, completion: { (didFinish) in
            self.tv.removeFromSuperview()
    })
}

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataArr.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: SearchCell = self.tv.dequeueReusableCellWithIdentifier("searchCell") as! SearchCell
    cell.cellLabel.text = dataArr[indexPath.row]
    return cell;
}
}

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    我认为问题出在这条线。

    self.tv.frame.size.height = 100
    

    尝试设置整个框架,而不仅仅是高度。很确定 UIView 的 Frame 的属性是只读的。

    here

    如果这不起作用。也许尝试实施

    func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2011-10-20
      相关资源
      最近更新 更多