Can't change default layoutMargins of view

前端 未结 3 626
深忆病人
深忆病人 2021-01-13 09:26

Since ios 8.0 views have additional layoutMargins which by default has an 8 points values for every side.

When I try to change margins in viewDidL

相关标签:
3条回答
  • 2021-01-13 09:48

    You are trying to set the layout margin of a root view of a view controller. The root view behaves differently than any other view in the hierarchy in regard of the layout margins.

    Layout margins of a root view are managed exclusively by the view controller, you can not set them.

    From Apple documentation:

    If the view is a view controller’s root view, the system sets and manages the margins. The top and bottom margins are set to zero points. The side margins vary depending on the current size class, but can be either 16 or 20 points. You cannot change these margins.

    https://developer.apple.com/reference/uikit/uiview/1622566-layoutmargins

    0 讨论(0)
  • 2021-01-13 09:49

    I am not sure what the problem is.

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.layoutMargins = UIEdgeInsets(top:100, left:100, bottom:100, right:100)
        println(self.view.layoutMargins.top)
        println(self.view.layoutMargins.left)
        println(self.view.layoutMargins.right)
        println(self.view.layoutMargins.bottom)
    }
    

    This prints 100 for every margin. If you are trying to set the margins for subviews of that view, you will need to set them explicitly also. The call to self.view.layoutMargins only affects the layoutMargins of self.view.

    If you want your view's subviews to respect the layoutMargins of your view's superview, you will need to set preservesSuperviewLayoutMargins on your view.

    Reference Documentation

    0 讨论(0)
  • 2021-01-13 09:56

    I used KVO to detect the view.layoutMargins changes. And I found that the view itself would change the layoutMargins after customise during layoutSubViews processing.

    So just put your customise codes in viewDidLayoutSubviews method:

    - (void)viewDidLayoutSubviews
    {
        self.view.layoutMargins = UIEdgeInsetsMake(100.0f, 100.0f, 100.0f, 100.0f);
    }
    

    PS: Through these codes are OC, but I think it can also work for Swift. Hope this works for you!

    0 讨论(0)
提交回复
热议问题