全局变量vs用于创建UITableView的属性

时间:2014-06-09 18:40:55

标签: ios swift

我在viewDidLoad()方法中创建了tableview,它工作得很好,但是如果我想用其他方法访问我的tableview,我就不能这样做了。实现UITableView的最佳方法是什么。带闭包的变量,属性?

let maintable:UITableView=UITableView()
    maintable.frame=CGRectMake(0, 60, 320, 350)
    maintable.showsVerticalScrollIndicator=false
    maintable.delegate=self
    maintable.datasource=self
    self.view.adsubview(maintable)

带闭包的变量。这里maintable.delegate=self抛出错误

 let mytable:UITableView={

    let maintable:UITableView=UITableView()
    maintable.frame=CGRectMake(0, 60, 320, 350)
    maintable.showsVerticalScrollIndicator=false

    return maintable

}()

2 个答案:

答案 0 :(得分:0)

您需要将mainTableView声明为实例变量。它的范围目前仅限于您的viewDidLoad方法,即使表视图本身仍然存在(因为您在视图消失之前将其添加到视图中)。您还需要确保您的班级符合UITableViewDataSourceUITableViewDelegate协议。

class MyViewController : ViewController {
    var mainTable: UITableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        maintable.frame = CGRectMake(0, 60, 320, 350)
        maintable.showsVerticalScrollIndicator = false
        maintable.delegate = self
        maintable.dataSource = self
        self.view.addSubview(maintable)
    }
}

extension MyViewController: UITableViewDelegate {
    // lots of optional methods
}

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

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        // return the cell
    }
}

答案 1 :(得分:0)

class MyViewController : ViewController , UITableViewDelegate , UITableViewDataSource
{
    let mainTable: UITableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        maintable.frame = CGRectMake(0, 60, 320, 350)
        maintable.showsVerticalScrollIndicator = false
        maintable.delegate = self
        maintable.dataSource = self
        self.view.addSubview(maintable)
    }

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

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell = UITableViewCell dequeuereusablecellWithIdentifier("cell") as UITableViewCell

        cell.titlelabel.text = "Error Resolved"

        return cell
    }

}