iOS view visibility gone

John picture John · Feb 5, 2018 · Viewed 18.4k times · Source

I am new to iOS development.I want to toggle (hide/visible) a subview from parent view.In android there is a way to hide the visibility to gone.

In android

subView.setVisibility(View.GONE);

In iOS

subView.removeFromSuperview()

when i use above function it remove subViewConstraints and mess up my scroll view constraints.

topsubView.bottomAnchor.constraint(equalTo: bottomSubView.topAnchor, constant: 8).isActive = true

when i use the above code it works fine and hide subView.but when i want to make subView visible,it is not showing the subView.

topsubView.bottomAnchor.constraint(equalTo: bottomSubView.topAnchor, constant: 8).isActive = false
self.view.layoutIfNeeded()

Hope you understand my problem.Thanks in Advance.

Answer

Mukesh picture Mukesh · Feb 5, 2018

As I have worked on both iOS & Android, You need to play with constraint outlet in ios to achieve Android functioning. iOS Does not support automatically like Android native support on visibility GONE & VISIBLE

You need to hook the outlet of particular constraint(it may vertical/horizontal/height) you need to set it to 0 & need to manage your UI.

To Hide:

self.viewYourConstraint.constant = 0
self.yourView.hidden = true
self.view.layoutIfNeeded()

To Show:

self.viewYourConstraint.constant = 100//your constant value
self.yourView.hidden = false
self.view.layoutIfNeeded()

Note: If other constraints will be affected because of the update to the constraint above, the following must also need to be called:

self.yourView.setNeedsUpdateConstraints()

Cheers