Swift - UIViewController中的UITableView,UITableView函数未被调用。

27

我在一个UIViewController中插入了一个tableview。但是我的代码没有起作用。当我进行检查时,我发现没有任何tableview函数被调用。

    class CustomViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

        @IBOutlet weak var authorArticlesTableView: UITableView!

        var authorid: Int!
        var authorname: String!
        var articles: [JSON]? = []

        func loadArticles(){
            let url = "http:here.com/" + String(authorid) + "/"
            println(url)
            Alamofire.request(.GET, url).responseJSON { (Request, response, json, error) -> Void in
                if (json != nil){
                    var jsonObj = JSON(json!)
                    if let data = jsonObj["articles"].arrayValue as [JSON]?{
                        self.articles = data
                        self.authorArticlesTableView.reloadData()
                    }
                }
            }
        }
        override func viewDidLoad() {
            super.viewDidLoad()
            self.loadArticles()
            println("viewDidLoad")
        }

         func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
             println("numberOfRowsInSection")
            return self.articles?.count ?? 0
        }

         func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomTableViewCell
            cell.articles = self.articles?[indexPath.row]
            println("cellForRowAtIndexPath")
            return cell
        }


         func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            performSegueWithIdentifier("WebSegue", sender: indexPath) 
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
        }

有什么解决办法吗?

谢谢。


1
你设置了委托和数据源吗? - Asaf
4个回答

56

你需要将你的视图控制器设置为表格视图的代理/数据源:

viewDidLoad的结尾添加:

authorArticlesTableView.delegate = self
authorArticlesTableView.dataSource = self

17

设置表格的delegatedataSource

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

0
有时候,如果你忘记将UITableViewCell拖放到UITableView中,XCode就无法理解TableView有Cell。 默认情况下,当你将UITableView拖放到UIViewController中时,我看到UITableView有Cell。但是你还需要将UITableViewCell拖放到UITableView中。 这对我来说是有效的。

0

在你的情况下这样做是有意义的

 @IBOutlet weak var authorArticlesTableView: UITableView!

所以它会变成

 @IBOutlet weak var authorArticlesTableView: UITableView! {
        didSet {
            authorArticlesTableView.delegate = self;
            authorArticlesTableView.dataSource = self;
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接