【问题标题】:Index out of range when i use to celll( Swift)当我使用单元格时索引超出范围(Swift)
【发布时间】:2018-06-06 00:24:50
【问题描述】:

人们,当我尝试从不同单元格返回图像时,我遇到了这个问题 (线程1:致命错误:索引超出范围)

我在这里做什么? 我正在尝试构建 Instagram 克隆并在我的主视图控制器中显示应该显示的内容。我使用表格视图进行导航,该表格视图有 2 个具有不同标识符的单元格。单元格编号 1 它是一个标题,将用户表中的数据带到我的用户名标签和个人资料图像。和单元格 2 它的帖子它应该带来像图像和标题这样的帖子数据。我使用 firebase 数据库。

我的代码:

import UIKit

import FirebaseAuth

import FirebaseDatabase

class HomeViewController: UIViewController ,UITableViewDelegate  {


    @IBOutlet weak var tableview: UITableView!
    var posts = [Post]()
    var users = [UserD]()
    override func viewDidLoad() {
        super.viewDidLoad()

        tableview.dataSource = self
        loadposts()
        userDetal()

     //   var post = Post(captiontxt: "test", photoUrlString: "urll")
     //   print(post.caption)
     //   print(post.photoUrl)

    }

    func loadposts() {
        Database.database().reference().child("posts").observe(.childAdded){ (snapshot: DataSnapshot)in
            print(Thread.isMainThread)
              if let dict = snapshot.value  as? [String: Any]{
                let captiontxt = dict["caption"] as! String
                let photoUrlString = dict["photoUrl"] as! String
               let post = Post(captiontxt: captiontxt, photoUrlString: photoUrlString)
                self.posts.append(post)
                print(self.posts)
                self.tableview.reloadData()
            }
        }
    }
    func userDetal() {
        Database.database().reference().child("users").observe(.childAdded){ (snapshot: DataSnapshot)in
            print(Thread.isMainThread)
            if let dict = snapshot.value  as? [String: Any]{
                let usernametxt = dict["username"] as! String
                let profileImageUrlString = dict["profileImageUrl"] as! String
                let user = UserD(usernametxt: usernametxt, profileImageUrlString: profileImageUrlString)
                self.users.append(user)
                print(self.users)
                self.tableview.reloadData()
            }
        }
    }

    @IBAction func logout(_ sender: Any) {
        do {
            try Auth.auth().signOut()
        }catch let logoutErrorr{
            print(logoutErrorr)
        }
        let storyboard = UIStoryboard(name: "Start", bundle: nil)
        let signinVC = storyboard.instantiateViewController(withIdentifier: "SigninViewController")
        self.present(signinVC, animated: true, completion: nil)


    }

}

extension HomeViewController: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return posts.count

    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return users.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
         let cell = tableview.dequeueReusableCell(withIdentifier: "imagecell", for: indexPath) as! PostCellTableViewCell

        cell.postimage.image = nil

        cell.tag += 1
        let tag = cell.tag

        cell.captionLabel.text = posts[indexPath.row].caption

        let photoUrl = posts[indexPath.row].photoUrl

        getImage(url: photoUrl) { photo in
            if photo != nil {
                if cell.tag == tag {
                    DispatchQueue.main.async {
                        cell.postimage.image = photo

                    }
                }
            }
        }
        return cell
        } else if indexPath.row == 1 {
            let cell = tableview.dequeueReusableCell(withIdentifier: "postcell", for: indexPath) as! HeaderTableViewCell

            cell.userimage.image = nil

            cell.tag += 1
            let tag = cell.tag
            cell.usernamelabel.text = users[indexPath.row].username 
            //Error showing here????????????????????????????????????
            let profileImageUrl = users[indexPath.row].profileImageUrl

            getImage(url: profileImageUrl) { photo in
                if photo != nil {
                    if cell.tag == tag {
                        DispatchQueue.main.async {
                            cell.userimage.image = photo


                        }
                    }
                }
            }

            return cell
        }
        return UITableViewCell()

    }


    func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
            if error == nil {
                completion(UIImage(data: data!))
            } else {
                completion(nil)
            }
            }.resume()
}
}

【问题讨论】:

  • 你来错地方了。该网站不运行错误跟踪服务。如果您需要帮助,请说明您正在尝试做什么。甚至没有人知道您要显示什么样的数据。
  • 你的代码没有意义;每个用户都有一个部分,并且在行中显示帖子;但是然后你尝试使用 indexpath.row 来访问你的 users 数组,如果该行是 1 ,并且大概你在 users 数组中只有 1 个用户,所以你得到一个数组边界错误
  • 对不起我的朋友,我现在解释一下。因为我只是初学者

标签: ios swift uitableview uiimageview uiimage


【解决方案1】:

试试这个。

cell.tag = indexpath.row

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 感谢您的建议 :) 我一定会在回答时牢记这一点 :)
【解决方案2】:

users数组的内容是什么?

您确定要定义与用户一样多的部分或尽可能多的行吗? 在这种情况下使用

func numberOfRows(in tableView: NSTableView) -> Int {
    return users.count
}

如上所述,您需要完全重写 cellForRowAt

应该是这样的:

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

    if row < users.count {
        let user = users[row]
        if let cellView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CellID"), owner: self) {
            (cellView as! NSTableCellView).textField?.stringValue = user.name
            // do the same for all the fields you need to set
            return cellView
        } else {
            return nil
        }
    }
    return nil
}

【讨论】:

    【解决方案3】:

    thanx,我的朋友,我找到了收容我的牢房的好方法。对于帖子单元格,我只使用cellForRowAt 和帖子数据。对于标题单元格,我使用viewForHeaderInSection 但是我的用户数据是heightForHeaderInSection。为一个观点创造高度

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多