将数据从函数传递到表视图

时间:2016-07-01 00:01:49

标签: ios swift uitableview

我一直在尝试创建一个通过函数(func obtainData)获取网站数据的应用程序,并在tableView上显示一些数据。

我已经找到了关于如何从网站获取数据然后将其作为数组的部分,因此我可以使用indexpath.row但我无法找到传递数据的方法我得到的将它显示在tableView上。

任何想法!

由于

以下是我写的代码。

    import UIKit

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {



        var recommendation = ""
        var recommendationArray = ""
        var delExtraTextArray = [String]()
        var urlRecommendationArrayStart = [String]()
        var urlRecommendationArrayEnd = [String]()
        var RecommendationStart = [String]()
        var RecommendationEnd = [String]()

        // need the var below to make the recommendations as an array to be used in a table view as indexpath.row

       var cellNumber = [String]()
        var cellTitle = [String]()
        var cellDetails = [String]()




        @IBOutlet var tableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()
            obtainData()
            tableView.delegate = self
            tableView.dataSource = self


        }




        func obtainData () {

            var url = NSURL (string: "http://www.choosingwisely.org/societies/american-college-of-obstetricians-and-gynecologists")

            if url != nil {

                let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

                    if error == nil {

                        // to get all of the url content and covert them into string

                        var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding) as NSString!

                        // to get to a specific contect seperated by a string

                         self.urlRecommendationArrayStart = (urlContent?.componentsSeparatedByString("<ol class=\"society-ol\">"))!

                        if self.urlRecommendationArrayStart.count > 0 {

                             self.urlRecommendationArrayEnd = self.urlRecommendationArrayStart[1].componentsSeparatedByString("</ol>")

                           // print(self.urlRecommendationArrayEnd)

                            // to check if there is any extra not needed text at the end of the recommnedations in the source page

                             self.delExtraTextArray = self.urlRecommendationArrayEnd[0].componentsSeparatedByString("<p><a")

                            if self.delExtraTextArray.count > 0 {

                                self.recommendationArray self.delExtraTextArray[0] as! String
                                self.obtainRecommendationTitle()

   } else {

                                self.recommendationArray = self.urlRecommendationArrayEnd[0] as! String
                                self.obtainRecommendationTitle()

                                // print("method 2 worked")

                            }


                        } else {

                            self.textView.text = "Sorry, couldn't get the recommendation at this point. Please make sure to download the updated version of the app"
                        }


                    } else {

                        self.textView.text = "Please check connection then try again"

                    }

                })

                task.resume()



            } else {

                self.textView.text = "Please check connection then try again"

                }




        }


        // to get the title of each recommendation

        func obtainRecommendationTitle() -> Array<String> {

            for var i = 2; i < urlRecommendationArrayEnd[0].componentsSeparatedByString("<p>").count - delExtraTextArray.count ; i = i + 4 {

                self.RecommendationStart = self.delExtraTextArray[0].componentsSeparatedByString("<p>")

                 self.RecommendationEnd = RecommendationStart[i].componentsSeparatedByString("</p>")

                self.recommendationArray = self.RecommendationEnd[0] as! String

                self.cellTitle.append(recommendationArray)

            }

            return cellTitle
        }




        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return cellTitle.count
        }



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


            let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

            cell.textLabel?.text = cellTitle [indexPath.row]

            return cell

        }

2 个答案:

答案 0 :(得分:2)

您可以通过cellForRowAtIndexPath委托方法传递它。对于一个坚定的答案,这个问题太开放了,但是跟随任何一半不太合适的在线UITableView教程应该可以解决这个问题。

快速浏览一下这个内容似乎达到了基础:https://www.weheartswift.com/how-to-make-a-simple-table-view-with-ios-8-and-swift/

答案 1 :(得分:1)

我认为您需要的是使用您想要的数据配置表格视图单元格的内容。基于这个假设,你可以使用这样的东西:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("PUT_YOUR_CELL_IDENTIFIER_HERE") as? UITableViewCell {
        let stuff = yourArray[indexPath.row]
        stuff.some_property_you_want = the_value_you_want      
        return cell
    } else {
        return UITableViewCell()
    }
}

如果您展示一些代码或更好地解释您的问题,您将获得Stack Overflow上的人们更好的支持。

编辑(基于您的修改): 你使用普通细胞吗? 单元格是否有文本字段来放置您想要的字符串? 您是否在故事板中定义了单元格的标识符“cell”? 您是否已将tableView插座连接到tableView本身?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell {
        print("ENTERED HERE!")
        let myCellText = cellTitle[indexPath.row]
        //what is the result of this print?
        print("TEXT TO ADD: \(myCellText)")
        //(...)
        cell.textLabel?.text = myCellText    
        return cell
    } else {
        return UITableViewCell()
    }
}

这些印刷品的结果是什么?