【问题标题】:Filling UITableView cell from remote database从远程数据库填充 UITableView 单元格
【发布时间】:2016-03-23 17:11:54
【问题描述】:

我遇到了 UITableView 的问题。

我想用从远程数据库获取的数据动态填充其单元格,因此数据到达之前需要一些时间。

代码如下:

class MailBoxViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var users: [NSDictionary] = []

override func viewDidLoad() {
    super.viewDidLoad()

    // call to rest API code to get all users in [NSDictionary]
    (...)

    // set table view delegate and data source
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

// set number of sections within table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

// set number of rows for each section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return self.users.count
    }
    return 0
}

// set header title for each section
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "Users"
    }
}

// set cell content for each row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // deque reusable cell
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

    // set item title
    if indexPath.section == 0 {
        cell.textLabel?.text = self.users[indexPath.row]["firstname"] as? String
    }
    return cell
}
}

问题是,当调用 tableView 函数为每个部分设置行数并为每行设置单元格内容时,我的 [NSDictionary] 用户仍然是空的。

只有在调用 rest API 代码以获取 [NSDictionary] 中的所有用户之后,我如何才能设置行和单元格?

感谢您的任何反馈。

问候

【问题讨论】:

    标签: ios swift uitableview ios9


    【解决方案1】:

    当您从 API 获得响应时,您应该设置self.users = arrayOfUsersYouReceivedFromServer,然后调用self.tableView.reloadData()。这个

    【讨论】:

    • 是的,但是当第一次调用数据源方法时,self.users 是空的,所以它因为数组越界异常而崩溃。
    • 我不明白你怎么会在这里超出范围。您返回用户数的数组计数。如果没有用户,则不会调用cellForRowAtIndexPath: 方法。
    【解决方案2】:

    填充users 后,调用tableView.reloadData()。这将再次调用您的数据源方法。

    【讨论】:

      【解决方案3】:

      当您完成获取用户后,请致电tableView.reloadData()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多