简体   繁体   中英

UIView is not hiding when I add it programmatically to UIstackview

I am new to xamarin ios and xcode . I have a tableview cell which has UILabel , a switch and a horizontal UIStackView (Center alignment, Distribution - Equal spacing). I have created a default UIView containing a textfield. This default view is added to the UIStackView in xib . In my program, I want to add a similar view to the right of the existing view and align it horizontally. I am also keeping a list of all input views added.

My problem is I am not able to hide the newly added views. If I remove the width constraints, then the width varies depending on placeholder text. If I remove the leading anchor constraints, then they are not aligned uniformly.

when I try to set the hidden property for the newly added view (subview of UIStackView ), it hides it but the space is left as is. I tried setting the constraints to false, used it with LayoutIfNeeded() but that doesn't help either.

Any other options available to actually hide the subview??

 UIView newView = new UIView();
 InputStack.AddArrangedSubview(newView);

 var newInput = new UITextField();
  newView.AddSubview(newInput);
  newInput.TranslatesAutoresizingMaskIntoConstraints = false;
  newInput.WidthAnchor.ConstraintEqualTo(175).Active = true;
  newInput.HeightAnchor.ConstraintEqualTo(35).Active = true;
  newInput.TopAnchor.ConstraintEqualTo(newView.TopAnchor).Active = true;
  newInput.LeadingAnchor.ConstraintEqualTo(InputList.Last().InputTextField.TrailingAnchor, 30).Active = true;

Please refer to this documentation about how to use UIStackView .

If you want to add items from left to right, there's no need to add the newView first then put your Control in the newView . You can directly put the newInput in the UIStackView . Also because you have used the horizontal StackView whose subViews will layout from leading to trailing automatically, the top and leading constraints can be omitted. Only width constraint is needed.

From your code, you use NSLayoutAnchor to add constraints. You should disable the previous constraint before you want to modify it:

//Define a field
NSLayoutConstraint WidthConstraint = null;

//When you want to modify the width, try to disable the previous one
if (WidthConstraint != null)
{
    WidthConstraint.Active = false;
}
WidthConstraint = Control.WidthAnchor.ConstraintEqualTo(0);
WidthConstraint.Active = true;

You can refer to my answer here for more details.

Or you can also remove the control directly. Then when you want to show it, add it again.

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