hide table view cell and remove table view space

1.8k Views Asked by At

I'm trying to hide table view and remove space. But the table view space not removed. When first time user coming this page there is no data inside the table view so I write ishidden=true.table hidden but space not remove.user add data manually and table view appear.this working proper after add data . I'm trying

self.tableView.tableFooterView = UIView()
self.tableView.ishidden=true

above code table hidden but not remove table space. So how to remove space of hide table view..

3

There are 3 best solutions below

0
On

If you just want to hide tableView then just set the tableView.alpha to 0 and disable tableView interaction. You can set your no data view before tableview in storyboard hierarchy and then manage with tableview alpha values to hide and show no data view

1
On

you can do with the help of tableview contentSize observer key.For that you have to take Outlet of tableview height and set into tableView observer method. Set tableView scroll disable.

 override func viewWillAppear(_ animated: Bool) {

        tbl.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        tbl.removeObserver(self, forKeyPath: "contentSize")
    }


    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if object is UITableView {
            print("contentSize:= \(tbl.contentSize.height)")
            self.heightTbl.constant = tbl.contentSize.height
        }
    }

Hope this will help you.

0
On

You need to set the height constraint for table view. The best place to set the height is numberOfSectionsInTableView function. This function called once on every reload of data.

//Assuming your data source
var dataSource: [String] = []

//connect this outlet to tableViewHeight Constraint
@IBOutlet var tableViewHeight: NSLayoutConstraint!

//connect this outlet to tableView
@IBOutlet var tableView: UITableView!

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

    //need to check the data availability
    if self.dataSource.count == 0{
        //need to set the table height constraint to zero
        self.tableViewHeight.constant = 0
        self.tableView.isHidden = true
        return 0
    }
    else {
        //need to set the table height constraint to desired frame.
        self.tableViewHeight.constant = self.view.frame.size.height //Assuming full screen.
        self.tableView.isHidden = false
        return 1

    }