Is there any way to add constraint between a view and the top layout guide in a xib file?

后端 未结 7 2326
时光说笑
时光说笑 2020-12-07 15:44

In iOS 7, we can now add a constraint between a view and the top layout guide, which I think is very useful to solve the status bar offset issue in iOS7(especially when ther

7条回答
  •  遥遥无期
    2020-12-07 15:59

    Cao Huu Loc's answer with swift 4

    extension NSLayoutConstraint {
    
        func constraintReplacing(firstItemWith newFirstItem: UILayoutSupport, withAttribute newFirstAttribute: NSLayoutAttribute) -> NSLayoutConstraint {
            return NSLayoutConstraint(item: newFirstItem, attribute: newFirstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant)
        }
    
        func constraintReplacing(secondItemWith newSecondItem: UILayoutSupport, withAttribute newSecondAttribute: NSLayoutAttribute) -> NSLayoutConstraint {
            return NSLayoutConstraint(item: firstItem as Any, attribute: firstAttribute, relatedBy: relation, toItem: newSecondItem, attribute: newSecondAttribute, multiplier: multiplier, constant: constant)
        }
    }
    
    class YourViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            for constraint in view.constraints {
                if constraint.firstItem === view && constraint.firstAttribute == .top {
                    let newConstraint = constraint.constraintReplacing(firstItemWith: topLayoutGuide, withAttribute: .bottom)
                    view.removeConstraint(constraint)
                    view.addConstraint(newConstraint)
                }
                if constraint.secondItem === view && constraint.secondAttribute == .top {
                    let newConstraint = constraint.constraintReplacing(secondItemWith: topLayoutGuide, withAttribute: .bottom)
                    view.removeConstraint(constraint)
                    view.addConstraint(newConstraint)
                }
            }
        }
    }
    

提交回复
热议问题