Ошибка индекса вне диапазона ПОСЛЕ кнопки в ячейке работает? - PullRequest
0 голосов
/ 16 марта 2020

Я добавляю кнопку в ячейку TableView. Tableview работает успешно, который показывает все данные, которые я хочу. После того, как я нажал кнопку, которая была установлена ​​в ячейке, код успешно выполняется, но после этого он сообщает об ошибке, что индекс выходит за пределы диапазона. Насколько я понимаю, ошибка говорит о том, что после того, как я нажал кнопку, в массиве нет элемента Почему это случилось?

** ПРИМЕЧАНИЕ: ошибка появляется в этой строке:

let followerid = ArrayFollowersID[indexPath.row]

Вот мой код

class FollowersVC: UIViewController, UITableViewDelegate, UITableViewDataSource, 
    UISearchBarDelegate{

    @IBOutlet weak var FollowersTableView: UITableView!
    @IBOutlet weak var Searchbar: UISearchBar!
    var ref = Database.database().reference()
    var ArrFollowers = [NSDictionary?]()
    var FilterArrFollowers = [NSDictionary?]()
    var ArrayFollowersID : Array<String> = Array()

 override func viewDidLoad() {
        super.viewDidLoad()

        let userid = Auth.auth().currentUser?.uid

        Searchbar.delegate = self
         self.FollowersTableView.rowHeight = 67

        //  retrieve the followers users
        ref.child("profile").child(userid!).child("follower").observe(.childAdded, with: {(snapshot) in
            let followersID = String(snapshot.key)
            self.ArrayFollowersID.append(followersID)
            self.Searchbar.placeholder = "Search \(self.ArrayFollowersID.count) followers"

            self.ref.child("profile").child("\(followersID)").observe(.value, with: {(snapshot) in
                    self.ArrFollowers.append(snapshot.value as? NSDictionary)
                    self.FollowersTableView.insertRows(at: [IndexPath(row: self.ArrFollowers.count-1,section: 0)], with: UITableView.RowAnimation.automatic)
            })
        })
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if Searchbar.text != "" {
                       return FilterArrFollowers.count
                   }
                   return self.ArrFollowers.count
        }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "FollowersCell", for: indexPath) as! FollowersTableCell
            let follower : NSDictionary
            let userid = Auth.auth().currentUser?.uid
            let followerid = ArrayFollowersID[indexPath.row]

       cell.followaction = {
   self.ref.child("profile").child(userid!).child("following").observeSingleEvent(of: .value, with: { (snapshot) in

               if snapshot.hasChild(followerid){
                   cell.Followbutton.setTitle("Follow", for: .normal)
                   cell.Followbutton.setTitleColor(.systemBlue, for .normal)
                        self.ref.child("profile").child(userid!).child("following").child(followerid).setValue(nil)
                        self.ref.child("profile").child(followerid).child("follower").child(userid!).setValue(nil)
}
}
class FollowersTableCell: UITableViewCell{

    var followaction : (() -> ()) = {}

    @IBOutlet weak var Followbutton: UIButton!


    @IBAction func FollowButton(_ sender: Any) {
        followaction()
    }
}

Ответы [ 2 ]

0 голосов
/ 17 марта 2020

ОБНОВЛЕНИЕ : на основании упомянутого iOSDev проблема заключается в том, что я неправильно закодировал Array.count, так что код не может понять, какой массив должен отвечать на indexPath. Я исправил код, основанный на Array, как NSDictionairy, больше не String Array

0 голосов
/ 16 марта 2020

Сначала проверьте это условие в cellForRow

if indexpath.row < yourArrayList.count {
  // set your cell data
}

это условие поможет вам выйти из ошибки индекса вне диапазона

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...