1

I have a UITableView with about at least 60 cells inside that needs to fit and not scroll. How can I get it to fit? I have already tried:

CGRect frame = self.tableView.frame; 
frame.size.height = self.tableView.contentSize.height;
self.tableView.frame = frame;

As said in this answer here but in the comments it was mentioned that it would not work with very large lists and you can tell because the bounce will reveal more cells. There was not a solution provided for this. How can I fix this problem?

Community
  • 1
  • 1

1 Answers1

0

Obvious solution is to not use UITableView. You can create your contentView as normal view, either programatically or in xib, and then add it to your main view and connect it to the previous custom one using constraint. I have done it multiple times and it works like a charm.

var lastView: UIView? = nil

for item in model.items {

    var customView: CustomContentView

    let objects = NSBundle.mainBundle().loadNibNamed("CustomContentView", owner: self, options: nil)
    customView = objects.first! as! CustomContentView

    customView.translatesAutoresizingMaskIntoConstraints = false

    customView.setItemModel(item)

    viewWrap.addSubview(customView)

    viewWrap.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[customView]|", options: [], metrics: nil, views: ["customView": customView]))

    if lastView == nil {
        viewWrap.addConstraint(NSLayoutConstraint(item: customView, attribute: .Top, relatedBy: .Equal, toItem: viewWrap, attribute: .Top, multiplier: 1, constant: 0))
    } else {
        viewWrap.addConstraint(NSLayoutConstraint(item: customView, attribute: .Top, relatedBy: .Equal, toItem: lastView!, attribute: .Bottom, multiplier: 1, constant: 0))
    }

    lastView = customView
}

if lastView != nil {
    viewWrap.addConstraint(NSLayoutConstraint(item: viewWrap, attribute: .Bottom, relatedBy: .Equal, toItem: lastView!, attribute: .Bottom, multiplier: 1, constant: 17))
}

Then you just to make sure that your custom view can resize to fit the screen if there is too many of them. I assume you have some max limit and that they all can fit. If not, then you need to add it to scroll view.

Lope
  • 5,388
  • 4
  • 30
  • 40
  • Is there really no way to do it via UITableView? How can I load data and style them using this code? Thanks. – commandercorn Aug 20 '16 at 11:15
  • There might a way, but it won't be simple. You load the data same way as you would with table view, but instead of calling reloadData, you create your views as described in the answer. I am not sure what you mean by styling – Lope Aug 20 '16 at 11:54