【问题标题】:iOS UIScrollView's width is different from the width set in constraintiOS UIScrollView 的宽度与约束中设置的宽度不同
【发布时间】:2016-09-08 10:17:33
【问题描述】:

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

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)

【问题讨论】:

  • 添加滚动视图约束 x 和 y 位置。
  • 您目前的尺码等级是多少?
  • @MarcoSantarossa 我目前的尺码等级是 wCompact hRegular
  • @BhadreshKathiriya 我为 x 和 y 位置添加了以下内容,(Scroll View.leading =leading + 80)和(Scroll View.top = top + 90),但它仍然不起作用
  • @WayneHuang 是想要的尺码等级吗?你在使用不同的尺寸等级吗?

标签: ios swift uiscrollview autolayout


【解决方案1】:

您的问题是您正在使用尺寸等级wCompact hRegular 来处理此约束,因此如果您有另一个尺寸等级(例如不同的方向),则您没有可用的这些约束。

要为iPhone 设置约束,我建议以编程方式进行:

if (IDevice.currentDevice().userInterfaceIdiom == .Phone) {
    // Set constraints or a different UIVIew here 
}

如果您的应用程序仅适用于 iPhone,您可以使用类大小 Any-Any 避免以编程方式设置。

【讨论】:

  • 谢谢!你是对的。在我将尺寸等级设置为 wAny hAny 后,它就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
相关资源
最近更新 更多