如何在插入行之前向UITableViewCells添加标签?

时间:2019-06-30 15:21:56

标签: swift uitableview

我的目标是在将行插入到tableview中之前,为每个可见的UITableViewCell插入一个标签,上面写着“正在加载...”。

到目前为止,我有以下内容: 我有一个功能齐全的表视图,可加载正确数量的单元格以及每个单元格中要包含的信息。代码如下:

override func viewDidAppear(_ animated: Bool) {
    let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
    refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: attributes)
    refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
    MyChallengesTableView.addSubview(refreshControl) // not required when using UITableViewController

    self.BetCreatorUsernameArray.removeAll()
    self.BetDescriptionArray.removeAll()
    self.UserMoneyInBet.removeAll()
    self.BetTotalPoolArray.removeAll()
    self.BetEndDateArray.removeAll()

    loadData()

    self.MyChallengesTableView.reloadData()
}

//refresh table view action
@objc func refresh(refreshControl:UIRefreshControl) {
    // Code to refresh table view

    //refreshes tableview
    self.BetCreatorUsernameArray.removeAll()
    self.BetDescriptionArray.removeAll()
    self.UserMoneyInBet.removeAll()
    self.BetTotalPoolArray.removeAll()
    self.BetEndDateArray.removeAll()

    loadData()

    self.MyChallengesTableView.reloadData()

    //stops refreshing
    self.refreshControl.endRefreshing()
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.BetDescriptionArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyChallengesCell", for: indexPath) as! MyChallengesTableViewCell

    cell.BetDescriptionOutlet.text = BetDescriptionArray[indexPath.row]
    cell.UserMoneyInBetOutlet.text = ("Money In: $" + UserMoneyInBet[indexPath.row])
    cell.TotalBetPoolOutlet.text = ("Pool: $" + BetTotalPoolArray[indexPath.row])
    cell.BetEndDateOutlet.text = ("End Date: " + BetEndDateArray[indexPath.row])
    cell.BetCreatorUsername = BetCreatorUsernameArray[indexPath.row]

    cell.betInformation = ["BetDescription" : BetDescriptionArray[indexPath.row],
                           "BetAmount" : UserMoneyInBet[indexPath.row],
                           "TotalMoneyInBet" : BetTotalPoolArray[indexPath.row],
                           "BetEndDate" : BetEndDateArray[indexPath.row],
                           "BetCreatorUsername" : BetCreatorUsernameArray[indexPath.row]]

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return CGFloat(152)
}

@objc func loadData(){
    //get username of current user
    self.databaseRef.child("Users").child((Auth.auth().currentUser?.uid)!).child("Username").observeSingleEvent(of: .value, with: {(snapshot) in

        self.currentUserUsername = snapshot.value as! String

    //make dictionary for each bet that a user is in
        self.databaseRef.child("UserBets").child(self.currentUserUsername).observeSingleEvent(of: .value, with: {(snapshot1) in

            if snapshot1.exists(){

            let UserBetsDictionary = snapshot1.value as! NSDictionary
                for (Bet, _) in UserBetsDictionary {

    //get bet information from the bets in database
                    self.databaseRef.child("Bets").child((Bet as? String)!).child("BetInfo").observeSingleEvent(of: .value, with: {(snapshot2) in

                        let BetInfoDictionary = snapshot2.value as! NSDictionary

                        self.BetCreatorUsernameArray.append((BetInfoDictionary["Creator Username"] as! String))
                        self.BetDescriptionArray.append((BetInfoDictionary["BetDescription"] as! String))
                        self.UserMoneyInBet.append((BetInfoDictionary["BetAmount"] as! String))
                        self.BetTotalPoolArray.append((BetInfoDictionary["TotalMoneyInBet"] as! String))
                        self.BetEndDateArray.append((BetInfoDictionary["BetEndTime"] as! String))

                        //insert the rows
                        if self.BetCreatorUsernameArray.count != 0 {
                            self.MyChallengesTableView.insertRows(at: [IndexPath(row:self.BetCreatorUsernameArray.count-1, section:0)], with: UITableViewRowAnimation.automatic)

                        }
                    })
                }
            }
        })
    })
}

我现在不确定代码是否太重要。简而言之,我想在ViewDidAppear中运行功能“ loadData”之前添加标签,然后在运行该功能并插入行后隐藏标签。

1 个答案:

答案 0 :(得分:1)

我认为它将适合您,只需进行如下扩展即可:

extension UITableView {

  func startLoading() {
    let view = UIView()
    separatorStyle = .none
    let activityIndicatorView = UIActivityIndicatorView(style: .gray)
    activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(activityIndicatorView)
    activityIndicatorView.startAnimating()
    activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -10).isActive = true
    activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

    let label = UILabel()
    label.textColor = UIColor.lightGray
    label.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(label)
    label.text = "Loading..."
    label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 10).isActive = true
    label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

    label.font = UIFont.systemFont(ofSize: 14)
    self.backgroundView = view
  }

  func stopLoading() {
    clearTableView()
  }

  func clearTableView() {
    separatorStyle = .singleLine
    self.backgroundView = nil
  }

}

然后在请求之前在tableView实例上调用方法startLoading,并在请求结果上调用stopLoading方法。