简体   繁体   English

如何使用大型列表调整UITableView的大小以适应所有内容而无需滚动?

[英]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. 我有一个UITableView,里面至少有60个单元格,需要适合而不是滚动。 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. 显而易见的解决方案是不使用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. 您可以以编程方式或在xib中将普通视图创建为contentView,然后将其添加到主视图中,并使用约束将其连接到以前的自定义视图。 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. 如果没有,那么您需要将其添加到滚动视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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