Adjust the size of UITableView dynamically which w

2019-09-15 19:12发布

I'm working on a project in Swift 3.0 and it has a UITableView inside a UIScrollView that has already been set its constraints.

The requirement is to display a list of songs that would return from an array in this UITableView, but the size of this UITableView should dynamically arrange according to the size of the array, so I do not need to scroll the UITableView since I can see all the songs in the UITableView (this UITableView is inside my scrollView, so instead I can use my scrollView do move up or down the list).

How would I achieve this?

2条回答
老娘就宠你
2楼-- · 2019-09-15 19:31

You can change height of the tableview based on the content.

var frame = tableView.frame
frame.size.height = tableView.contentSize.height
tableView.frame = frame

If you are using autolayout create outlet for tableview height and assign tableview content size to its constant.

tableviewHeightConstraint.constant = tableview.contentSize.height
查看更多
老娘就宠你
3楼-- · 2019-09-15 19:41

1.Create a subclass for tableView and override intrinsicContentSize.

         class MyOwnTableView: UITableView {
        override var intrinsicContentSize: CGSize {
            self.layoutIfNeeded()
            return self.contentSize
        }

        override var contentSize: CGSize {
            didSet{
                self.invalidateIntrinsicContentSize()
            }
        }

        override func reloadData() {
            super.reloadData()
            self.invalidateIntrinsicContentSize()
        }
    }

2. In Interface builder change the class of your tableView to MyOwnTableView (subclass of UITableView).

  1. Set automatic row height for the table view.

        tableView.estimatedRowHeight = 60.0
        tableView.rowHeight = UITableViewAutomaticDimension
    
查看更多
登录 后发表回答