如何以编程方式更改布局边距

时间:2017-08-24 12:54:54

标签: ios swift autolayout

我在viewDidLoad中设置非常简单,只需添加一个视图,然后通过“锚点”将其固定到superview的边距上。式:

let myView = UIView(frame: .zero)
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
myView.backgroundColor = UIColor.red
myView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
myView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
myView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true
myView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true
view.layoutMargins = .zero

问题是在模拟器中运行时仍有余量。为什么忽略layoutMargins归零?

enter image description here

4 个答案:

答案 0 :(得分:1)

您需要在// throw exception because var attribute doesn't accept el <c:remove var="${sessionScope[Constant.ATT_SESSION_MESSAGE]}" scope="session" /> <c:remove var="${Constant.ATT_SESSION_MESSAGE}" scope="session" /> // don't remove anything <c:remove var="Constant.ATT_SESSION_MESSAGE" /> // work but the name is hard coded <c:remove var="session_message" scope="session" /> UIViewController方法

中添加此内容
viewWillLayoutSubviews()

但是如果你需要override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() view.layoutMargins = .zero view.layoutMarginsDidChange() } 的保证金,你可以像我在评论中所说的那样使用.zero

答案 1 :(得分:1)

试试这个。

3

Apple document以供参考。

答案 2 :(得分:0)

iOS 11似乎已修复/更改。较低版本运气不佳。

我在this question

中详细阐述了更多内容

答案 3 :(得分:0)

不要忘记self.view.insetsLayoutMarginsFromSafeArea = false,它将添加到您设置为self.view.directionalLayoutMarginsself.view.layoutMargins的任何值上