【问题标题】:Having trouble adding subviews to scrollview无法将子视图添加到滚动视图
【发布时间】:2017-07-31 20:51:17
【问题描述】:

我能够初始化我的滚动视图并使用背景颜色设置它的 contentSize...完成后一切正常,但是当我使用以下代码将子视图添加到滚动视图时,我无法看到这些视图...请帮助?

func setupViews(_ views: [NewView]) {
    var multiplier: CGFloat = 0.0
    let width = frame.size.width
    let height = frame.size.height
    for view in views {
        let newView = NewView()
        addSubview(newView)
        newView.frame = CGRect(x: width * multiplier, y: 0, width: width, height: height)
        newView.backgroundColor = .random()
        newView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        newView.centerXAnchor.constraint(equalTo: centerXAnchor, constant: width * multiplier).isActive = true
        multiplier += 1
    }
    contentSize = CGSize(width: width * multiplier, height: height)
}

我在 NewView 类中有一个 commonInit() 函数,它在必需的 init 和 override init 中都被调用,可能会有所帮助,所以在这里

private func commonInit() {
    translatesAutoresizingMaskIntoConstraints = false
    backgroundColor = UIColor.white

    let labels = [nameLabel, brandLabel, priceLabel]
    var multiplier: CGFloat = 0.0

    for label in labels {
        addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 10.0 * multiplier).isActive = true
        label.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0.0).isActive = true
        multiplier += 1.0
    }

}

【问题讨论】:

  • 如果您要使用自动布局约束设置视图的位置,那么您还必须使用它们来设置大小。

标签: ios swift


【解决方案1】:

您的问题是,当调用 translatesAutoresizingMaskIntoConstraints 时,.frame 或 .frame.size 等方法将被忽略/覆盖(取决于您何时使用它们,在 translatesAutoresizingMaskIntoConstraints 之前或之后)。 如Apple所述:

请注意,自动调整掩码约束完全指定了视图的 大小和位置;因此,您不能向 在不引入冲突的情况下修改此大小或位置。如果你 想使用 Auto Layout 来动态计算大小和位置 根据您的观点,您必须将此属性设置为 false,然后提供 视图的一组明确、不冲突的约束。

在这个post中有很好的描述

原因是使用.frame 实际上最终会创建自动布局约束,当您将translatesAutoresizingMaskIntoConstraints 设置为false 时会删除这些约束。所以你需要决定是使用 set .frame 方法,还是只使用约束。

为了简单起见,我通常最终做的是在大型视图上使用.frame(比如可能占据整个屏幕并且需要在后面移动的 UIView),并使用自动布局以编程方式在它的子视图上,在那个更大的视图中可能没有动画。

另外,请注意多次调用布局方法,它可能会根据调用时间覆盖某些内容。

【讨论】:

  • 非常感谢您的反馈和其他帖子的链接进一步解释translatesAutoResizingMaskIntoConstraints
  • 我最终重写了代码并使用视觉约束来处理布局而不是@murphguy
猜你喜欢
  • 2014-09-10
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
相关资源
最近更新 更多