【问题标题】:TableView.reloadData() is not working ? (SWIFT)TableView.reloadData() 不工作? (迅速)
【发布时间】:2015-12-04 02:44:31
【问题描述】:

我正在开发一个从 JSON 中提取问题的测验应用程序。我已经多次为 TableView 使用 reloadData 并按预期工作。但现在我正在使用 Alamofire 获取问题并将其保存在数组中并从数组中获取问题。

但它返回 Array is Out of Index.

如何在第一个单元格中显示数组的第一项?

风险投资

class ExamController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var Exam: UITableView!

    var CourseID : String!
    var EID : String!
    var EName : String!
    var ET : String!

    var QArray : [String] = []

    var progress = GradientCircularProgress()


    override func viewDidLoad() {
        super.viewDidLoad()
        progress.show(style:MyStyle())
        // JUST TRIED
        dispatch_async(dispatch_get_main_queue(), {
            self.getQuestions()
            // DO SOMETHING ON THE MAINTHREAD
            self.Exam.reloadData()
        })

        self.Exam.tableFooterView = UIView(frame: CGRectZero)
        self.Exam.tableFooterView?.hidden = true
    }

    func getQuestions(){

        if ET == "CHAPTER" {
            Alamofire.request(.GET, "http://www.wis.com/index.php/capp/chapter_questions_details/\(CourseID)/\(EID)/10")
                .responseJSON { (_, _, data, _) in
                    println(data)
                    let json = JSON(data!)
                    let catCount = json.count
                    for index in 0...catCount-1 {
                        let q = json[index]["QUESTION"].string
                        self.QArray.append(q!)
                        println(self.QArray)
                    }

            }

            self.progress.dismiss()
            self.Exam.reloadData()

        } else if ET == "FA" {
            Alamofire.request(.GET, "http://www.wis.com/index.php/capp/fa_questions_by_course_id/\(CourseID)/\(EID)")
                .responseJSON { (_, _, data, _) in
                    println(data)
                    let json = JSON(data!)
                    let catCount = json.count
                    for index in 0...catCount-1 {
                        let q = json[index]["QUESTION"].string
                        self.QArray.append(q!)
                        println(self.QArray)
                    }

            }
                        self.progress.dismiss()
                        self.Exam.reloadData()
    }
}

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell = self.Exam.dequeueReusableCellWithIdentifier("Question") as! QuestionCell

            cell.Questionlabel?.text = QArray[0]
            return cell

        }
        else
        {
            let cell = self.Exam.dequeueReusableCellWithIdentifier("Option") as! OptionCell

            cell.Optionlabel?.text = "Option"
            return cell

        }
    }

【问题讨论】:

  • numberOfRowsInSection 必须动态返回数据源中的项目数,而不是静态值
  • 在你调用reloadData的地方写上println声明。我猜在您的数据返回之前会调用重新加载。日志应该会显示调用顺序。
  • @vadian 我的数组有 100 多个问题。但我的 TableView 中只需要 5 行
  • @PhillipMills 在我的 Alamofire 请求完成之前,表格视图首先加载:(
  • 对于功能,请使用Code convention 并用小写字符命名你的变量。像aVariable,而不是Variable。如果是 examaExam。不是Exam

标签: ios arrays swift uitableview alamofire


【解决方案1】:

听起来您需要将重新加载放入完成处理程序中,以便在尝试更新 UI 时获得数据。

为了安全起见(以防其他调用 reload),您还可以通过检查 QArray 中是否至少有 5 个项目来保护您在 numberOfRowsInSection 中的返回值。

【讨论】:

    【解决方案2】:

    您需要在Alamofire 块内重新加载您的表格视图

    所以它看起来像

      Alamofire.request(.GET, "http://www.wis.com/index.php/capp/chapter_questions_details/\(CourseID)/\(EID)/10")
                .responseJSON { (_, _, data, _) in
                    println(data)
                    let json = JSON(data!)
                    let catCount = json.count
                    for index in 0...catCount-1 {
                        let q = json[index]["QUESTION"].string
                        self.QArray.append(q!)
                        println(self.QArray)
                    }
            self.progress.dismiss()
            self.Exam.reloadData()
      }
    

    当然是的,根据给定的答案和 cmets,

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.QArray?.count ?? 0 // will return 0 rows if QArray is empty
    }
    

    这可能会有所帮助!

    【讨论】:

    • 问题是我的 QArray 有超过 100 个项目。但我只希望行数为 5。我该怎么做?
    • 你使用的是哪个数据库?
    • 我没有使用任何数据库
    • 那么数据从哪里来?如果您将我的解决方案应用到 numberOfrows = 5 会发生什么?
    • 我正在尝试实现这个 UI i.imgur.com/xUGtMU9.png。我通过 API 从 JSON 中获取问题。但是我必须在我的表格视图中只显示一个问题,然后是我的答案数组中的四个选项。
    【解决方案3】:

    使用调度队列在 .responseJSON 中调用您的完成处理程序,并从那里更新您的 UI。

    例如

    Alamofire.request(.GET, postEndpoint, headers: headers)
            .responseJSON { response in 
    
        // Do something...
    
        dispatch_async(dispatch_get_main_queue(), {
            // Update your UI here
            self.tableView.reloadData()
         })
    }
    

    【讨论】:

    • 谢谢,很有帮助!!
    猜你喜欢
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多