如何在UITableView

时间:2015-12-19 11:10:17

标签: ios swift uitableview uiviewcontroller

我有UIViewController,其中嵌入了UITableView。如果为我的ViewController类添加了一个插座。

因为我不希望ViewController过于沉重,所以我想将UITableViewDataSource协议和UITableViewDelegate协议的方法放在不同的类中。

所以我创建了一个TableViewDataSource.swift和一个TableViewDelegate类:

class TableViewDelegate : NSObject, UITableViewDelegate {
    //custom code here if required
}

class TableViewDataSource : NSObject, UITableViewDataSource {
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

       return 1
    }
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cellIdentifier = "MyCellIdentifier"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)

        cell.textLabel?.text = "left text"
        cell.detailTextLabel?.text = "right text"

        return cell


    }


}

class ViewController: UIViewController {

    @IBOutlet var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = TableViewDataSource()
        tableView.delegate = TableViewDelegate()

        tableView.setNeedsDisplay()

        // Do any additional setup after loading the view, typically from a nib.
    }
}

在我的故事板中,我在tableView中创建了一个原型单元格,其中包含标识符" MyCellIdentifier"。我使用这个标识符在我的TableViewDataSource方法中创建一个单元格。

但是,如果我运行应用程序,我只会看到一个空的tableView。即使我已经在ViewController的viewDidLoad方法中设置了这些方法,这些方法甚至都不会被调用。我还尝试通过调用setNeedsDisplay来强制执行tableView重绘。这也没有效果。

enter image description here

1 个答案:

答案 0 :(得分:5)

您已走上正轨,我相信您的问题很容易解决。见这里:

tableView.dataSource = TableViewDataSource()
tableView.delegate = TableViewDelegate()

这会创建一个新的TableViewDataSource和一个新的TableViewDelegate,并分别将它们分配给dataSourcedelegate。以下是UITableView上的这些属性:

weak public var dataSource: UITableViewDataSource?
weak public var delegate: UITableViewDelegate?

注意weak位?您正在创建它们并将它们分配给一个弱小的属性,因此它们会很快被抛弃。

您的解决方案是为视图控制器中的这两个新对象创建属性,然后在viewDidLoad()中创建这些属性并将其发送到表视图中。

相关问题