0

I am using below code for the UITableView, in every cell there are two buttons configured to perform certain actions as shown in the code. Earlier it was working fine, but now As I update this code to new version of Xcode it is not working, whenever I tap on the cell or the button in the cell it doesn't perform any action, neither it shows any error, but it just darkens the half of the cell with grey colour?

Xcode earlier was 10 and now 11, swift 5 version same in both cases

There is one fixed cell at the top and then there is list of cells as per the number of documents in the database

What could be the issue?

for information I am using Swift IOS and cloud firestore database

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
        }


     }








}
Jan Hernandez
  • 4,414
  • 2
  • 12
  • 18
  • Try stepping through your code and see what happens. Also, and this could be related, you are doing a lot of forced unwrapping of optionals. It's better to use something like `if button = sender as? UIButton { ... }`. Similar for all the strings. – koen Nov 29 '19 at 14:51
  • but earlier it was working, I tried but couldn't figure out –  Nov 29 '19 at 14:54
  • So the **only** thing that changed was the Xcode and Swift version? Try setting the Swift version in your project back to what it was before. Bug could have always been there, but is now exposed after your upgrade. – koen Nov 29 '19 at 14:57
  • Also, please include the Xcode and Swift versions before and after (in your question, not in the comments). Thank you. – koen Nov 29 '19 at 14:57
  • @koen but other tableviews are working as they were working earlier, only in this case the issue happened –  Nov 29 '19 at 15:00
  • Then look for differences in the code and storyboard between the tableViews that are working and this one. Something must cause the issue. – koen Nov 29 '19 at 15:02
  • @koen can that be issue with "SceneDelegate" which I removed from info.plist as well? –  Nov 29 '19 at 15:28
  • I'm still on Xcode 10, but did you try putting it back? – koen Nov 29 '19 at 16:14
  • This SO post may have your answer: https://stackoverflow.com/questions/35357505/uibutton-not-responding-used-in-a-custom-uitableviewcell/35357595 – koen Nov 29 '19 at 16:41
  • 1
    that didn't worked, but deleting the buttons in storyboard and reconfiguring them worked out –  Nov 29 '19 at 18:03

1 Answers1

0

Do this in tableview cellForRowAt function before return cell:

cell.selectionStyle = .none
  return cell

this will fix the issue