表格单元格中的按钮无法点击

Posted

技术标签:

【中文标题】表格单元格中的按钮无法点击【英文标题】:Button in the table cell not working upon tapping 【发布时间】:2019-11-29 14:40:37 【问题描述】:

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

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

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

可能是什么问题?

关于我正在使用 Swift ios 和 cloud 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
        


     









【问题讨论】:

尝试单步调试您的代码,看看会发生什么。此外,这可能是相关的,您正在对选项进行大量强制解包。最好使用if button = sender as? UIButton ... 之类的东西。所有字符串都类似。 但早些时候它可以工作,我试过但无法弄清楚 那么唯一改变的是Xcode和Swift版本?尝试将项目中的 Swift 版本设置回之前的版本。错误可能一直存在,但现在在升级后暴露。 另外,请包括之前和之后的 Xcode 和 Swift 版本(在您的问题中,而不是在 cmets 中)。谢谢。 没用,但删除情节提要中的按钮并重新配置它们成功了 【参考方案1】:

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

cell.selectionStyle = .none
  return cell

这将解决问题

【讨论】:

然后增加你的按钮尺寸可能是它的尺寸太小,用户无法点击。 我删除了按钮,然后重新配置它们现在可以正常工作了,感谢您的建议

以上是关于表格单元格中的按钮无法点击的主要内容,如果未能解决你的问题,请参考以下文章

当点击另一个按钮时,取消选择表格视图单元格中的按钮

点击保存按钮并存储在字典中时获取表格视图单元格中的文本字段?

在表格视图中点击按钮 - 错误的单元格

如何为自定义表格视图单元格中的按钮单击获取不同的视图控制器

当触摸单元格中的自定义按钮时,我们如何知道表格中触摸了哪个单元格?

表格视图中的按钮没有响应其单元格编号