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

标签 ios swift uiscrollview autolayout

我是 iOS 自动布局的新手。我想使用启用分页的 UIScrollView 实现一个 View 分页器。我把scrollView设置为(w, h) to (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)

最佳答案

你的问题是你正在为这个约束使用尺寸类 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/

相关文章:

ios - UIBarButtonItem : Image offsets

ios - 从 Firebase 打印数据

ios - 将数组和字符串传递给自定义 UIView 类(子类)(iOS)

iOS 8 - 按钮在水平 ScrollView 中没有响应

ios - 如果我共享我的 React-Native 应用程序,我是否需要将 ios 和 android 文件夹放入源代码管理中?

ios - UITabBarController 选项卡栏项目标题在 Xib 中不可见

ios - IPv6 应用商店拒绝

ios - UICollectionView 在横向模式下对右侧 w-h 像素滑动无响应

ios - CGColorRef 对象数组

javascript - 如何在 Angular Js 应用程序上启用双击