我有覆盖整个屏幕的 UIScrollView
,在其中我有 3 个并排的 UIView
对象,通过分页进行管理。我想做出正确的约束,以便它也适合 iPhone 6。
拖动时是这样的:
UIScrollView
的约束运行良好,但是如何在 UIScrollView
中安排 View 的约束?
提前致谢!!
最佳答案
您的 ScrollView 的 subview 需要两组约束。
第一组是规定 ScrollView 的滚动行为(即 ScrollView 的
contentSize
是什么)。我们使用 ScrollView 的contentLayoutGuide
为了这。请注意,与大多数约束不同,这并不规定 subview 的大小,而只是规定这些 subview 与 ScrollView 的contentSize
之间的关系。第二组是 subview 大小的约束。为此,我们使用 ScrollView 的
frameLayoutGuide
.
因此,假设您有三个 subview ,分别是红色、绿色和蓝色,您可以这样做:
// Set horizontal constraints relative to scroll view contentLayoutGuide
NSLayoutConstraint.activate([
redView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
greenView.leadingAnchor.constraint(equalTo: redView.trailingAnchor),
blueView.leadingAnchor.constraint(equalTo: greenView.trailingAnchor),
blueView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
])
// set constraints that are common to all three subviews
for subview in [blueView, greenView, redView] {
NSLayoutConstraint.activate([
// Set vertical constraints to scroll view contentLayoutGuide
subview.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
subview.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
// Set width and height of subviews relative to scroll view's frame
subview.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor),
subview.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor),
])
}
上面假设你已经关闭了这三个 subview 的 translatesAuthresizingMaskIntoConstraints
。但希望以上说明了这个想法。
顺便说一下,您也可以在 IB 中完成所有这些操作(引用“内容布局指南”和“框架布局指南”,就像上面一样)。我只是在此处以编程方式执行此操作,因此您可以确切地看到发生了什么。
在 iOS 11 之前,我们没有 contentLayoutGuide
和 frameLayoutGuide
。因此,当您在 ScrollView 及其 subview 之间设置约束时,它的作用类似于 contentLayoutGuide
(即仅影响 contentSize
和 subview 的关系)并设置实际大小在 subview 中,您必须到达 ScrollView 的父 View :
// Set horizontal constraints relative to scroll view contentSize
NSLayoutConstraint.activate([
redView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
greenView.leadingAnchor.constraint(equalTo: redView.trailingAnchor),
blueView.leadingAnchor.constraint(equalTo: greenView.trailingAnchor),
blueView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
])
// set constraints that are common to all three subviews
for subview in [blueView, greenView, redView] {
NSLayoutConstraint.activate([
// Set vertical constraints to scroll view contentSize
subview.topAnchor.constraint(equalTo: scrollView.topAnchor),
subview.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
// Set width and height of subviews relative to superview
subview.widthAnchor.constraint(equalTo: view.widthAnchor),
subView.heightAnchor.constraint(equalTo: view.heightAnchor),
])
}
顺便说一下,Apple 在 Technical Note TN 2154 中讨论了这种行为.
但如果针对 iOS 11 及更高版本,请使用更直观的 contentLayoutGuide
和 frameLayoutGuide
。
关于ios - 对带有分页的 UIScrollView 的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877857/