Anilkumar iOS Developer
Anilkumar iOS Developer

Reputation: 3755

Tableview creating multiple times inside cellforrowatindexpath delegate method

I have two tableviews in my screen. 1 is maintableview, 2 is inside 1st tableviewcell I am displaying this 2nd tableview. So, I am able to differentiating while displaying date for each tableview.

But, Issue is, once I pressed on 2nd tableview cell data, I am reloading particular cell of 1st tableview cell, inside that cell I am created 2nd tableview, so, Whenever I pressed on 2nd tableview cell, 2nd tableview is repeatedly creating and adding to 1st tableviewcell.

So, code is follows inside cellforrowatindexpath delegate method

//1st tableview delegate method and reloading this indexpath multiple times by whenever clicking 2nd tableview cells data

else if indexPath.row == 1 {
//some action doing code

//later 2nd tableview creation
            //for no of event days like day1, day2 etc
                noOfEventDaysTableView = UITableView(frame: CGRect(x:(cell?.secondCircleGraph.frame.maxX)! + 5,y:10,width:60,height:50), style: .plain)
                cell?.contentView.addSubview(noOfEventDaysTableView)
                noOfEventDaysTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
                noOfEventDaysTableView.delegate = self
                noOfEventDaysTableView.dataSource = self
                noOfEventDaysTableView.backgroundColor = UIColor.clear
                noOfEventDaysTableView.separatorColor = UIColor.clear
                noOfEventDaysTableView.rowHeight = 20.0

}

While scrolling 2nd tableview data, its coming like creating again cells. PFA.

enter image description here

How to avoid once created 2nd tableview, second restrict to create again?

I can avoid by doing following

         noOfEventDaysTableView.removeFromSuperview()

Is there any better solution for this? Any suggestions. Thanks!

Upvotes: 0

Views: 704

Answers (2)

Aman Gupta
Aman Gupta

Reputation: 179

If you are adding tableview as a "addSubview(noOfEventDaysTableView)" in "cellForRowAt indexPath" . Then please add them in tableview cell methods awakeFromNib().

override func awakeFromNib() {
    super.awakeFromNib()
    noOfEventDaysTableView = UITableView(frame: CGRect(x:(cell?.secondCircleGraph.frame.maxX)! + 5,y:10,width:60,height:50), style: .plain)
    cell?.contentView.addSubview(noOfEventDaysTableView)
    // Initialization code
}

And for compare the table view set the tag value for tableView

tableView.tag = 999

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

This problem occurs because of dequeuing so,Enumerate the contentView of the main tableView cell before adding to check for existence of any UITableView subView if not exists add it . . .

Upvotes: 0

Related Questions