当我使用celll时,索引超出范围(Swift)

时间:2017-12-23 23:36:02

标签: ios swift uitableview uiimageview uiimage

人们,当我从不同的单元格中尝试图像时,我遇到了这个问题 (线程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()
}
}

3 个答案:

答案 0 :(得分:0)

尝试这个。

1. root=Tk()
2. root.geometry("640x480")
3. root.title("Skroutz Parser")

#entryText=StringVar(root)
4. topFrame=Frame(root, bg='cyan', width = 640, height=80)
5. middleFrame=Frame(root,bg='gray2', width=640, height=400)
6. bottomFrame=Frame(root, bg='yellow', width = 640, height=50)

# layout all of the main containers
7. root.grid_rowconfigure(1, weight=1)
8. root.grid_columnconfigure(0, weight=1)

9. topFrame.grid(row=0)
10.middleFrame.grid(row=1)
11.bottomFrame.grid(row=2)

# layout middle container
12.middleFrame.grid_rowconfigure(0, weight=1)
13.middleFrame.grid_columnconfigure(0, weight=1)

14.leftFrame=Frame(middleFrame, bg='green', width = 125, height=400)
15.rightFrame=Frame(middleFrame, bg='white', width = 515, height=400)

16.leftFrame.grid(row=0,column=0,sticky="n")
17.rightFrame.grid(row=0, column=1)

18.buttonFeatured=Button(leftFrame, text='   Recommended    ', pady=5, .command=showRecommendedProductsResults)
19.buttonSkroutz=Button(leftFrame, text='Skroutz Products', pady=5, command=printSkroutzProducts)
20.buttonFeatured.grid(row=0, column=0, sticky="n")
21.buttonSkroutz.grid(row=1, column=0)

22.entryText=StringVar()
23.entryMain=Entry(rightFrame,textvariable=entryText, bg="white")
24.entryMain.grid(row=0,column=0,rowspan=2,columnspan=5,sticky="w")

25.root.mainloop()

答案 1 :(得分: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
}

答案 2 :(得分:0)

thanx,我的朋友,我找到了一个很好的方法来收容我的细胞。对于post cell,我只使用cellForRowAt和post数据。对于标题单元格我使用viewForHeaderInSection 但我的用户数据为heightForHeaderInSection。为视图创造高点