简体   繁体   中英

Swift - UITableView inside UIViewController, UITableView functions are not called

I inserted a tableview inside a UIViewController. But my code is not working. When I checked I found that none of the tableview functions are not called.

    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)
        }

Any solution for this?

Thanks,

You have to set your view controller as a table view delegate/datasource:

add to the end of the viewDidLoad :

authorArticlesTableView.delegate = self
authorArticlesTableView.dataSource = self

Set table delegate and dataSource :

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

Sometimes, if you forget to drap and drop UITableViewCell to UITableView. XCode don't understand TableView has Cell. By default, when you drap and drop UITableView into UIViewController. I see UITableView has Cell. But you need to drap and drop UITableViewCell into UITableView also.

It is work with me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM