假设我的布局如下图所示: Root View - 是 viewController 的 View 。我希望我的页脚文本是
- 如果内容适合一个屏幕(主要文本很小),则粘在屏幕底部
- 在其他情况下距正文 15pt,距屏幕底部 15pt
我知道,我可以计算主要文本高度并将其与当前屏幕尺寸进行比较,但我想找到另一种方法(理想情况下只有在有限制的情况下)。
这可能吗?
最佳答案
要实现您正在尝试做的事情,您需要设置以下约束:
ScrollView :
- top
、leading
、trailing
和 bottom
等于 RootView 的 top
、leading
、trailing
和 bottom
包装 View :
- top
、leading
、trailing
和 bottom
等于 ScrollView 的 top
、leading
、trailing
和 bottom
- width
等于 ScrollView 的 width
- height
greaterThanOrEqual to ScrollView 的 height
TextView :
- top
, leading
和 trailing
等于 WrapperView 的 top
, leading
和 trailing
页脚 View :
- leading
和trailing
等于WrapperView 的leading
和trailing
- bottom
等于 WrapperView 的 bottom
(常量为 15)
- top
greaterThanOrEqual to TextView's bottom
(常量为 15)
关键是使用 greaterThanOrEqual
关系的两个约束:WrapperView 至少与 ScrollView 和 一样高>FooterView 的顶部距离 TextView 的底部至少有 15 的距离。
以下是使用 Storyboard时的限制条件:
这就是您以编程方式(使用 SnapKit)执行此操作的方式:
import UIKit
import SnapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let scrollView = UIScrollView()
view.addSubview(scrollView)
let wrapperView = UIView()
wrapperView.backgroundColor = .cyan
scrollView.addSubview(wrapperView)
let textView = UILabel()
textView.numberOfLines = 0
textView.font = UIFont.systemFont(ofSize: 30)
textView.text = "You think water moves fast? You should see ice. It moves like it has a mind. Like it knows it killed the world once and got a taste for murder. After the avalanche, it took us a week to climb out. Now, I don't know exactly when we turned on each other, but I know that seven of us survived the slide... and only five made it out. Now we took an oath, that I'm breaking now. We said we'd say it was the snow that killed the other two, but it wasn't. Nature is lethal but it doesn't hold a candle to man."
//textView.text = "You think water moves fast? You should see ice. It moves like it has a mind."
textView.backgroundColor = .yellow
wrapperView.addSubview(textView)
let footer = UILabel()
footer.textAlignment = .center
footer.text = "Footer text"
footer.backgroundColor = .orange
wrapperView.addSubview(footer)
scrollView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
wrapperView.snp.makeConstraints { (make) in
make.edges.equalTo(scrollView)
make.width.equalTo(scrollView)
make.height.greaterThanOrEqualTo(scrollView)
}
textView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(0)
}
footer.snp.makeConstraints { (make) in
make.top.greaterThanOrEqualTo(textView.snp.bottom).offset(15)
make.left.right.equalTo(0)
make.bottom.equalTo(-15)
}
}
}
长文本截图:
带有短文本的屏幕截图:
关于用于 ScrollView 和粘性页脚的 iOS Autolayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611395/