繁体   English   中英

表格单元格中的按钮在点击时不起作用

[英]Button in the table cell not working upon tapping

我正在为 UITableView 使用以下代码,在每个单元格中都有两个按钮配置为执行代码中所示的某些操作。 早些时候它工作正常,但现在当我将此代码更新到新版本的 Xcode 时,它​​不起作用,每当我点击单元格或单元格中的按钮时,它都不会执行任何操作,也不会显示任何错误,但是它只是用灰色使单元格的一半变暗?

之前的 Xcode 是 10,现在是 11,swift 5 版本在两种情况下都相同

顶部有一个固定单元格,然后根据数据库中的文档数量列出单元格

可能是什么问题?

有关信息,我正在使用 Swift IOS 和云 Firestore 数据库

class HomeViewController: UITableViewController {



    var posts = [Post]()
    var db: Firestore!

    var scores1 = [Scores]()

    var postAuthorId:String = ""
    var postAuthorname:String = ""
    var CommentAuthorName:String = ""
    var PostTitle:String = ""
    var postAuthorGender:String = ""
    var postAuthorEmail:String = ""
    var postAuthorfullname:String = ""
    var postAuthorSpinnerC:String = ""
    var postContent:String = ""
    var postCategory:String = ""
    var postAuthorPicUrl:String = ""
    var postTimeStamp:String = ""
    var l11:Int = 0


    var postKey:String = ""
    private var documents: [DocumentSnapshot] = []






    override func viewDidLoad() {
        super.viewDidLoad()
        db = Firestore.firestore()

        tableView.dataSource = self
        tableView.delegate = self


        retrieveAllPosts()
        getuserscores()

        var AViewController: UIViewController = UIViewController()
        var MyTabBarItem: UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "pencil")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), selectedImage: UIImage(named: "pencil"))
        AViewController.tabBarItem = MyTabBarItem
        // Do any additional setup after loading the view.
     //   navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleLogout))
    }

    func getuserscores(){
        let userRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid)

        userRef.getDocument{(document, error) in
            if let document = document, document.exists{
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                let l1 = document.get("l1") as! Int
                let l2 = document.get("l2") as! Int
                let l3 = document.get("l3") as! Int
                let l4 = document.get("l4") as! Int

                let newScores = Scores(_l1: l1, _l2: l2, _l3: l3, _l4: l4)
                self.scores1.append(newScores)


            }
              self.tableView.reloadData()
        }


    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func retrieveAllPosts(){
        let postsRef = Firestore.firestore().collection("posts").order(by: "timestamp", descending: true).limit(to: 50)

        postsRef.getDocuments { (snapshot, error) in

            if let error = error {

                print(error.localizedDescription)

            } else {

                if let snapshot = snapshot {

                    for document in snapshot.documents {


                        let data = document.data()
                        let username = data["post_author_username"] as? String ?? ""
                        let postTitle = data["postTitle"] as? String ?? ""
                        let postcategory = data["postcategory"] as? String ?? ""
                        let postContent = data["postContent"] as? String ?? ""
                        let postAuthorProfilePicUrl = data["post_user_profile_pic_url"] as? String ?? ""
                        let postAuthorSpinnerC = data["post_author_spinnerC"] as? String


                        let newSourse = Post(_documentId: document.documentID, _username: username, _postTitle: postTitle, _postcategory: postcategory, _postContent: postContent, _postuserprofileImagUrl: postAuthorProfilePicUrl, _postAuthorSpinncerC: postAuthorSpinnerC)

                            self.posts.append(newSourse)
                    }
                    self.tableView.reloadData()
                }
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
               tableView.estimatedRowHeight = 200
               tableView.rowHeight = UITableView.automaticDimension


    }

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return scores1.count + posts.count

    }


     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 && scores1.count == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SmileMiles") as! ScoresCellInHomeScreen

            cell.set(scores: scores1[indexPath.row])
            return cell
        } else if posts.count > (indexPath.row - 1 ) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell

            cell.btnComment.tag = indexPath.row - 1
            cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)

            cell.favoritebutton.tag = indexPath.row - 1
            cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
            cell.set(post: posts[indexPath.row - 1 ])
            return cell
        } else {
            return UITableViewCell()
        }
    }

    @objc func favupdate(_ sender: AnyObject) {

        let commentbutton = sender as! UIButton
        let post = posts[commentbutton.tag]
        postKey = post._documentId // or what key value it is

        let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("marked_posts").document(postKey)
        let postRef = Firestore.firestore().collection("posts").document(postKey)



        postRef.getDocument{(document, error) in
            if let document = document, document.exists{
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                self.postAuthorId = document.get("post_author_id") as! String
                self.postAuthorname = document.get("post_author_username") as! String
                self.PostTitle = document.get("postTitle") as! String
                self.postContent = document.get("postContent") as! String
                self.postAuthorEmail = document.get("post_author_email") as! String
                self.postCategory = document.get("postcategory") as! String
                self.postAuthorfullname = document.get("post_author_fullname") as! String
                self.postAuthorGender = document.get("post_author_gender") as! String
                self.postAuthorPicUrl = document.get("post_user_profile_pic_url") as! String
                // let l11:Bool = document.get("l1") as! Bool
                //  self.postTimeStamp = document.get("post_timeStamp") as! String
                self.postAuthorSpinnerC = document.get("post_author_spinnerC") as! String

            }

            let postObject = [
                "post_author_gender": self.postAuthorGender,
               // "post_author_dateOfBirth": self.dateOfBirth,
                "post_author_spinnerC": self.postAuthorSpinnerC,
                "post_author_fullname": self.postAuthorfullname,
                "post_author_id": self.postAuthorId,
                "post_author_username": self.postAuthorname,
                "post_author_email": self.postAuthorEmail,
                "postTitle": self.PostTitle,
                "postcategory": self.postCategory,
                "postContent": self.postContent,
               // "post_timestamp": FieldValue.serverTimestamp(),
                "post_user_profile_pic_url":self.postAuthorPicUrl,
                "post_id": self.postKey

                ] as [String : Any]



            userMarkRef.setData(postObject, merge: true) { (err) in
                if let err = err {
                    print(err.localizedDescription)
                }
                print("Successfully set new user data")
            }

        }



    }

   override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 150

        }
        else{
            return UITableView.automaticDimension
        }
    }

    @objc func toComments(_ sender: AnyObject) {

        let commentbutton = sender as! UIButton
        let post = posts[commentbutton.tag]
        postKey = post._documentId // or what key value it is
        print(postKey + "hello")
        performSegue(withIdentifier: "toCommentsList", sender: self)

    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "toCommentsList"){
     var vc = segue.destination as! CommentListViewController
     vc.postId = postKey
        }


     }








}

在返回单元格之前在 tableview cellForRowAt 函数中执行此操作:

cell.selectionStyle = .none
  return cell

这将解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM