iOS8 layoutMargin被忽略

时间:2014-11-21 04:33:21

标签: ios swift ios8

我以编程方式生成多个视图。有一个超级视图,其余是超级视图的子视图。

我在superview上设置layoutMargins:

mySuper.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10);
mySuper.preservesSuperviewLayoutMargins = true;

然后我像这样设置子视图:

mySub = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0));
mySuper.addSubview(mySub);

目标是让mySub从左上角和左上角放置10个点。或者一般情况下,覆盖x ymySuper 0点的内容。

虽然这不起作用。而是将mySub放置在顶部和左侧边缘上。我误解了layoutMargins的假设吗?我刚刚开始学习iOS开发。

1 个答案:

答案 0 :(得分:0)

layoutMargin仅适用于自动布局。例如

mySuper.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

let mySub = UILabel()
mySuper.addSubview(mySub)
mySub.setTranslatesAutoresizingMaskIntoConstraints(false)

mySuper.addConstraint(NSLayoutConstraint(item: mySub, attribute: .Top, relatedBy: .Equal, toItem: mySuper, attribute: .TopMargin, multiplier: 1, constant: 0) )
mySuper.addConstraint(NSLayoutConstraint(item: mySub, attribute: .Left, relatedBy: .Equal, toItem: mySuper, attribute: .LeftMargin, multiplier: 1, constant: 0) )
/* OR
mySuper.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[subview]", options: nil, metrics: nil, views: ["subview":mySub]))
mySuper.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[subview]", options: nil, metrics: nil, views: ["subview":mySub]))
*/
mySub.text = "Label"