iOS UIScrollView的宽度与约束中设置的宽度不同

时间:2016-09-08 10:17:34

标签: ios swift uiscrollview autolayout

我是iOS自动布局的新手。我想使用UIScrollView实现一个视图寻呼机,并启用分页。我将scrollView设置为(w,h)为(200,65),但scrollView的宽度在运行时始终为240。结果,内容的偏移量(我添加到scrollView中的标签)与scrollView的宽度不匹配。他们为什么不同?如何获得正确的宽度?

enter image description here enter image description here

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)

1 个答案:

答案 0 :(得分:1)

这里的问题是你使用大小等级iPhone来解决这个问题,所以如果你有另一个大小等级(例如不同的方向),你就不会有这些约束。

if (IDevice.currentDevice().userInterfaceIdiom == .Phone) { // Set constraints or a different UIVIew here } 设置约束我建议以编程方式进行:

Any-Any

如果您的应用程序仅适用于iPhone,则可以使用班级大小#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> void main() { pid_t pid; pid = fork(); //parent sleeps while the child has exited //not an orphan since parent still alive //child will be still present in process table if(pid==0) {//child exit(0); } else {//parent sleep(15); } } ,避免以编程方式设置。