2016-11-25 61 views
1

我怎样才能写入以下代码使用NSLayoutConstraints(或)在UIView子类自动布局代替autoresizingMask

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,谢谢。

回答

-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) 
+0

感谢您的答案,但它有一些问题:必须在添加约束之前将视图添加为子视图。我的目标是不要用另一种观点来填补子类 - 但要在中心有一个正方形,边长比为1:1。 –

+0

@这只是填充超级视图。不是OP想要的。 – BangOperator

-1

我已经通过复制粒度等级相同的行为,但只针对iPhone手机。检查这个故事板。 (它不是代码,你问什么)

Storyboard

由于ipad公司有宽度:Regaular和高度:常规,现在看来,这是不可能的iPad,而无需使用layoutSubview

+0

感谢您的回答,它可以像您提到的那样工作,也可以用于单个/少数控制器。不幸的是,我的目标是重复使用这个子类(作为背景或其他) - 为了能够保持它们全部是最新的,它应该被分类。 –

+0

Downvoters,请解释相同的原因! – BangOperator