当我使用单元格时索引超出范围(Swift)

问题描述 投票:-4回答:3

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

我在这做什么?我正在尝试构建一个Instagram克隆,并在我的家庭视图控制器中显示帖子应该显示的内容。我使用表视图进行导航,并且该表视图有2个具有不同标识符的单元格。单元格编号1它是一个标题,用于将users表中的数据添加到我的用户名标签和配置文件图像中。它的帖子数据如图像和标题,它的帖子数据和帖子数量为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()
}
}
ios swift uitableview uiimageview uiimage
3个回答
0
投票

试试这个。

cell.tag = indexpath.row

0
投票

用户数组的内容是什么?

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

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
}

0
投票

我的朋友,我发现了一个很好的方法来控制我的细胞。对于post cell,我只使用cellForRowAt而不是post数据。对于标题单元格我使用viewForHeaderInSection但我的用户数据使用heightForHeaderInSection。使观点变得更高

© www.soinside.com 2019 - 2024. All rights reserved.