我是 iOS
自动布局的新手。我想使用启用分页的 UIScrollView
实现一个 View 分页器。我把scrollView设置为(w, h) to (200, 65),但是运行时scrollView的宽度一直是240。结果,内容的偏移量,即我添加到 scrollView 中的标签,与 scrollView 的宽度不匹配。他们为什么不同?如何获得正确的宽度?
private let contents = ["This is the 1st message",
"This is the 2nd message",
"This is the 3rd message"]
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
print("scrollView.bounds = \(scrollView.bounds)")
print("scrollView.frame = \(scrollView.frame)")
var x: CGFloat = 0
for content in contents {
let label = UILabel(frame: CGRectMake(x, 0, 0, 0))
label.text = content
label.sizeToFit()
print("label.frame = \(label.frame)")
scrollView.addSubview(label)
x += scrollView.bounds.width
}
scrollView.contentSize = CGSizeMake(x, scrollView.bounds.height)
}
Output:
scrollView.bounds = (0.0, 0.0, 240.0, 128.0)
scrollView.frame = (80.0, 156.0, 240.0, 128.0)
label.frame = (0.0, 0.0, 178.0, 20.3333333333333)
label.frame = (240.0, 0.0, 185.666666666667, 20.3333333333333)
label.frame = (480.0, 0.0, 182.333333333333, 20.3333333333333)
最佳答案
你的问题是你正在为这个约束使用尺寸类 wCompact hRegular
,所以如果你有另一个尺寸类(例如不同的方向),你就没有这些约束可用。
要为 iPhone
设置约束,我建议以编程方式进行:
if (IDevice.currentDevice().userInterfaceIdiom == .Phone) {
// Set constraints or a different UIVIew here
}
如果您的应用仅适用于 iPhone,您可以使用类大小 Any-Any
避免以编程方式设置。
关于iOS UIScrollView 的宽度与约束中设置的宽度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39388332/