【问题标题】:Using auto layout to arrange views in sequence with one taking whatever space is available使用自动布局按顺序排列视图,其中一个占用任何可用空间
【发布时间】:2015-06-09 15:12:33
【问题描述】:

我正在尝试水平排列 5 个视图,目前我的视觉格式和视图属性(省略颜色)如下所示:

let questionLabel = UILabel()
questionLabel.text = "Did you take any additional medication?"
questionLabel.lineBreakMode = .ByWordWrapping
questionLabel.numberOfLines = 0

let questionSwitch = UISwitch()

let noLabel = UILabel()
noLabel.text = "No"
let yesLabel = UILabel()
yesLabel.text = "Yes"

for v in [questionLabel, questionSwitch, noLabel, yesLabel] {
    scrollView.addSubview(v)
    v.setTranslatesAutoresizingMaskIntoConstraints(false)
}
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-20-[label]-(>=10,==10@900)-[no(==25)]-5-[switch]-5-[yes(==30)]-10-|",
        options: .AlignAllCenterY, metrics: nil,
        views: ["label":questionLabel, "switch":questionSwitch, "no":noLabel, "yes":yesLabel]))

我已经硬编码了“否”和“是”标签的宽度,因为它有时会试图使它们变大,这会导致出现更大的边距。我希望有一个灵活大小的唯一边距是在问题和“否”标签之间。

当屏幕的宽度大到足以将label 的文本放在一行时,这很有效,但是当它必须进行换行时,会以一种不受欢迎的方式转移内容:

它确实将标签分成 2 行,但随后在开关顶部挤压“是”。调试器中没有关于破坏约束的警告。我错过了什么?

【问题讨论】:

    标签: ios swift autolayout


    【解决方案1】:

    通常,当我遇到这样的情况时,我发现将相关项目放入自己的视图中是最有用的。在这种情况下,我认为您可以将开关及其标签放入自己的视图中。这样它就可以单独处理自己的布局。我在一个示例项目中尝试了这个,它对我有用:

    let switchContainerView = UIView()
    for v in [noLabel, questionSwitch, yesLabel] {
        switchContainerView.addSubview(v)
        v.setTranslatesAutoresizingMaskIntoConstraints(false)
    }
    
    let viewBindings = ["label":questionLabel, "switch":questionSwitch, "no":noLabel, "yes":yesLabel, "switchContainerView":switchContainerView]
    switchContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[no(==25)]-5-[switch]-5-[yes(==30)]|", options: .AlignAllCenterY, metrics: nil, views: viewBindings))
    
    for v in [questionLabel, switchContainerView] {
        view.addSubview(v)
        v.setTranslatesAutoresizingMaskIntoConstraints(false)
    }
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-20-[label]-(>=10,==10@900)-[switchContainerView]-10-|", options: .AlignAllCenterY, metrics: nil, views: viewBindings))
    

    我所做的是创建switchContainerView 并添加开关及其标签。我分别为那个容器上的开关做了布局。

    【讨论】:

    • 感谢(>=10,==10@900)。我没想到你能做到。
    • 这是一个好的开始。它没有立即工作,但我能够对 switchContainerView 施加额外的约束以强制其宽度。
    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多