简体   繁体   中英

Access UIViewController from View

I have this UIView which has its constraints, constraints is set to the parent view, which is UIViewController , every time I set the constraints, I have to pass the currentViewController so it can do this:

currentViewController.view.addConstraint(...)

I want the view to be able to set the constraint, in whichever view it is, I want to give my view responsibility to set the constraints to its parents without having to pass it as an argument, how do I do it? I've seen some answers in Objective-C but I want to do it in Swift, and I don't know how to.

I've tried using view.superView but it didn't work.

Yes, you should definitively use view.superview to setup constraints. But pay attention, you should add constraints only when your view is part of that hierarchy, which means, it should be already inside a view ( view.superview != nil ).

As a flow, you should first add your view as a subview to another view, than adjust the constraints based on the view.superview .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM