Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace UIView with another UIView, keep constraints

Tags:

ios

swift

uiview

My view can be in a few states, lets say .enabled and .disabled. The disabled and enabled view are wastly different, except for the fact that their content are centered on the screen.

During runtime the conditions can change, and the view should be updated accordingly, in other words, I might want to remove the disabled view, and add the enabled view.

Would it be possible to update a subview without adding new constraints?

I have sort of solved the issue using a containerView;

private var containerView: UIView = {
    let containerView = UIView()
    containerView.translatesAutoresizingMaskIntoConstraints = false

    return containerView
}()

That I add to the view the old fashined way

addSubview(containerView)

Set constraints;

NSLayoutConstraint.activate([
    containerView.centerYAnchor.constraint(equalTo: .centerYAnchor)
    containerView.leadingAnchor.constraint(equalTo: .leadingAnchor),
    containerView.trailingAnchor.constraint(equalTo: .trailingAnchor)
])

Then when I'd like to switch view, I would do something like;

    var state: ViewState? {
        didSet {
            guard let state = state else { return }

            // Remove previously added view
            containerView.subviews.forEach({ $0.removeFromSuperview() })

            var contentView: UIView

            switch state {
            case .disabled:
                contentView = disabledView
            case .enabled:
                contentView = enabledView
            }

            containerView.addSubview(contentView)

            NSLayoutConstraint.activate([
                contentView.topAnchor.constraint(equalTo: containerView.topAnchor),
                contentView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
                contentView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
                contentView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
            ])
        }
    }

So the center constraints I need to keep alive would be on the containerView, and would never be removed.

Is there a cleaner way to achieve this result? or any direct problems you see with this approach?

like image 295
sch Avatar asked Nov 20 '25 11:11

sch


1 Answers

You should use Container View. In centre keep container view and update child view as per your state. You center view constraint will remain same. Just child view will hide/show

Here is reference link to check more about Container View: https://medium.com/@dushyant_db/setting-up-a-container-view-using-interface-builder-and-via-code-7ac1a7f0a0d6

like image 190
Mitesh Avatar answered Nov 23 '25 00:11

Mitesh