【问题标题】:UILayoutPriority in an UIScrollView doesn't affect anythingUIScrollView 中的 UILayoutPriority 不会影响任何内容
【发布时间】:2019-07-28 22:21:26
【问题描述】:

我有一个内容视图(在 xib 文件中定义),其中有一些标签和两个按钮(屏幕截图 1.a 上的白色视图)。如果我们来了它是如何显示在屏幕上的,让我画出方案;

ViewController View -> View (Custom View Class) -> UIScrollView -> ContentView (Xib file)

按钮放置在与下边距相关的位置。他们都放在底部。顶部按钮有一个约束,它有 10 个与最后一个标签底部相关的常量(这是 greater than equal constraint 并且有 5 个 UILayoutPriority)。

问题:当我从按钮到标签甚至大于等于时,按钮仅在标签下方堆叠 10 点。即使底部有这么大的差距。 (截图 2.a)

我想要实现的目标: 我想要如果所有内容都适合屏幕,从最后一个标签到第一个按钮至少有 10 个约束,不要滚动。如果没有,请滚动。

自定义视图类:

override init(frame: CGRect) {
    super.init(frame: frame)
    initialize()
}
func initialize() {
    self.translatesAutoresizingMaskIntoConstraints = false
    let name = String(describing: type(of: self))
    let nib = UINib(nibName: name, bundle: .main)
    nib.instantiate(withOwner: self, options: nil)

    cancelButton.layer.borderColor = UIColor.darkGray.cgColor
    cancelButton.layer.borderWidth = 1.0

    scrollView.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(self.scrollView)
    scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
    scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    scrollView.addSubview(contentView)

    self.contentView.translatesAutoresizingMaskIntoConstraints = false
    //self.contentView.clipsToBounds = true

    contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
    contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
    contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
    contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true 
}

示例截图:

如果内容适合视图,我想要下图。如果不是按钮可以向上直到它适合,如果它不适合即使,视图应该是可滚动的。

截图 2.a

【问题讨论】:

    标签: ios swift uiscrollview autolayout nslayoutconstraint


    【解决方案1】:

    以下行应该足以计算滚动视图中内容的高度,并为您提供您期望的正确行为。

    contentView.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.heightAnchor).isActive = true
    

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多