【问题标题】:autolayout instead of autoresizingMask自动布局而不是 autoresizingMask
【发布时间】:2016-11-25 10:02:18
【问题描述】:

我如何在 UIView 子类中使用 NSLayoutConstraints(或 anchors)编写以下代码?

func commonInit() {
    aView                  = UIView()
    aView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

    addSubview(aView)
}

override func layoutSubviews() {
    super.layoutSubviews()

    let smallerSide = min(bounds.width, bounds.height)

    aView.bounds = CGRect(x: 0.0, y: 0.0, width: smallerSide, height: smallerSide)
    aView.center = CGPoint(x: bounds.midX, y: bounds.midY)
}

一个目标是避免使用layoutSubviews()。 此外,aView 必须保持 1:1 的纵横比。 如果您需要更多信息,请告诉我。

PS:请让我们使用swift3,谢谢。

【问题讨论】:

    标签: ios swift autolayout constraints


    【解决方案1】:

    检查以下代码:

    let view = UIView(frame: CGRectZero)
        view.setTranslatesAutoresizingMaskIntoConstraints(false)
        super.init(frame: frame)
        let viewsDict = ["view": view]
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
        addSubview(view)
    

    【讨论】:

    • 感谢您的回答,但它有一些问题:必须先将视图添加为子视图,然后才能添加约束。我的目标是不要用另一个视图填充子类 - 而是在中心有一个正方形,边比为 1:1。
    • @这只是填充超级视图。不是 OP 想要的。
    【解决方案2】:

    我已经通过尺寸等级复制了相同的行为,但仅适用于 iPhone。检查这个故事板。 (不是代码,是你要的)

    Storyboard

    由于 iPad 具有 width:Regaular 和 Height:Regular,因此 iPad 似乎无法使用 layoutSubview

    【讨论】:

    • 感谢您的回答,它可以像您提到的那样工作,并且适用于单个/几个控制器。不幸的是,我的目标是大量重用该子类(作为背景或其他东西)——为了使它们都保持最新,它应该被子类化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多