UITableView within a UITableViewCell with dynamic height

前端 未结 3 1976
执笔经年
执笔经年 2021-01-27 07:50

So I\'m trying to build something rather intricate - potentially more than what the picture below shows. Anyway..

I\'m trying to have a UITableView inside o

相关标签:
3条回答
  • 2021-01-27 08:26

    You should use UIStackView instead UITableView in cells, because as i understood, inner tableViews will not scroll or dequeue. That will be misusage of UITableView. If you have already cells or you insist, you may set height constraint of inner tableview at layoutSubviews method of inner tableview's parent view by taking tableviews content size.

    0 讨论(0)
  • 2021-01-27 08:31

    You can do with Observer, please try if it works

    1. You have to add to tableview (which is in tableCell)

    yourTableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.old, context: nil)
    

    2. Method that observe changes

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
         //height can be use as cell height,
        let height = yourtableview.contentSize.height;
    }
    
    deinit {
         yourtableview.removeObserver(self, forKeyPath: "contentSize")
    }
    
    0 讨论(0)
  • 2021-01-27 08:41

    You can subclass UITableView and turn it into an "auto-sizing" table view, based on its contents:

    final class ContentSizedTableView: UITableView {
        override var contentSize:CGSize {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
        override var intrinsicContentSize: CGSize {
            layoutIfNeeded()
            return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
        }
    }
    

    Now, the table view will behave very similar to a multi-line UILabel --- just set up your constraints in the same way.

    Two notes:

    1) Disable scrolling on the ContentSizedTableView - not necessary but will probably be a better UX for your case.

    2) When you lay this out in your prototype cell, it will need a Height constraint to satisfy IB / Storyboard. So, add either

    • a >= height constraint (so you have a minimum height even if you have no rows), or
    • give it a "Placeholder" height constraint, or
    • give the height constraint a low priority

    Here is an example using a ContentSizedTableView in a scroll view. Same idea, and should make it clear how to use it:

    https://stackoverflow.com/a/56840758/6257435

    0 讨论(0)
提交回复
热议问题