简体   繁体   中英

How to resize UITableView with a large list to fit all the content without scrolling?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM