【发布时间】:2017-04-18 02:51:17
【问题描述】:
【问题讨论】:
标签: ios uiscrollview swift2 height
【问题讨论】:
标签: ios uiscrollview swift2 height
我们可以使用自动布局,我们在滚动视图中使用内容视图,可以将其固定到滚动视图,并且给定的高度和宽度约束等于主视图。然后,如果我们希望高度动态变化,我们可以给高度约束一个比其他约束低的优先级,因此内容视图的高度将根据其固有大小增加,因为它的子视图。
参考链接:
【讨论】:
首先你需要设置0的子视图高度约束,然后计算数据高度(你想在子视图中设置),并简单地分配subview.heightConstraint.constant = data.height,然后你需要设置scrollView.contentsize,它基于子视图身高:
self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: self.subViewHeight.constant)
【讨论】:
对我来说,这个技巧奏效了(Swift 4)
scrollView.layoutIfNeeded()
scrollView.isScrollEnabled = true
scrollView.contentSize = CGSize(width: self.view.frame.width, height: scrollView.frame.size.height)
【讨论】:
self.view代表什么?
viewDidLayoutSubviews 方法。此外,高度应设置为contentView.frame.size.height 而不是scrollView.frame.size.height,因为滚动视图框架是主框架的。
您必须计算内容所需的高度,包括间距。 将该值分配为行的高度并刷新表(或与行一起部分)
【讨论】:
垂直滚动视图根据标签文本长度调整大小的示例:
let scrollView = UIScrollView()
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.heightAnchor.constraint(lessThanOrEqualToConstant: UIScreen.main.bounds.height / 2).isActive = true
let bodyLabel = UILabel()
scrollView.addSubview(bodyLabel)
bodyLabel.translatesAutoresizingMaskIntoConstraints = false
bodyLabel.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
bodyLabel.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
bodyLabel.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
bodyLabel.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
bodyLabel.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
let heightConstraint = bodyLabel.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
heightConstraint.priority = .defaultLow
heightConstraint.isActive = true
【讨论】: