问题
i placed a table view and a view in a scroll view how to change the scroll view's height dynamically depending on the number of cells in the table view and the content present in content view also
回答1:
You need to set contensize of your ScrollView. You can do it by proper autolayout or programatically as
CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;
In Swift 3
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var contentRect = CGRect.zero
for view: UIView in scrollView.subviews {
contentRect = contentRect.union(view.frame)
}
contentRect.size.height = contentRect.size.height + 20
scrollView.contentSize = contentRect.size
}
In Swift 4
Here is a more concise version in Swift 4. Credit for Swift 4 to this ans
extension UIScrollView {
func updateContentView() {
contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
}
}
You can accomplish the same in storyboard. There is hack to accomplish that.
Add Constraints to scrollview top, left , right and height as 1000 or more as per requirement. Your Scroll View may exceed your view controller height itself.
Then you can add Constrain between your Scroll View Bottom & Last Subview (in your case View containing TableView and PaymentView ) Bottom as 0 or with 10.
3.You can now delete your height constraint.
But before this make sure consraints between all subviews of scrollview is proper.
Hope it helps. Happy Coding!!
回答2:
You only have to do 2 things to achieve this
satisfy all constraints of scrollview when adding view and tableview in it by adding constraints to all sides of scroll view so that scrollview can figure out its content size, but make sure give fixed height to tableview( we will later increase its height when loading remote data)
Now when you get data from remote url then after calling tableview reloadData you have to implement this method in your code
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for constraint in tableView.constraints{
if constraint.firstAttribute == .height{
constraint.constant = tableView.contentSize.height
break
}
}
self.view.layoutIfNeeded()
}
Then your tableview height will increase according to its content height and your scrollview content size will also increase then only your outer scrollview will scroll instead of tableview scrolling
来源:https://stackoverflow.com/questions/44839101/how-to-dynamically-increase-the-height-of-scroll-view