Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a UIView and remove the "empty" space? -iOS/Monotouch

I need to be able to hide controls on a page that uses constraints and remove the empty space that Hidden=true leaves. It needs to be similar to how the web handles visibility. If it's invisible, it doesn't take up space.

Does anyone know of a clean way to accomplish this?

Please let me know if you need more details. Thx


Example:

UIButton | UIButton | UIButton
"empty space for hidden UIButton"
UIButton 

That should really be rendered like this:

UIButton | UIButton | UIButton
UIButton 

Edit: I'm using Xamarin Studio and VS2012 for development.

like image 744
Christina Dessi Avatar asked Oct 22 '22 07:10

Christina Dessi


1 Answers

Since original question is related to Xamarin, I provide complete C# solution.

First, create height constraint for your view and give it an identifier in Xcode Interface Builder:

Constraint Identifier

Then in controller override ViewDidAppear() method and wrap view with HidingViewHolder:

    public override void ViewDidAppear(bool animated)
    {
        base.ViewDidAppear(animated);
        applePaymentViewHolder = new HidingViewHolder(ApplePaymentFormView, "ApplePaymentFormViewHeightConstraint");
    }

It is important to create HidingViewHolder when view was laid out, so it has real height assigned. To hide or show view you can use corresponding methods:

applePaymentViewHolder.HideView();
applePaymentViewHolder.ShowView();

HidingViewHolder source:

using System;
using System.Linq;
using UIKit;

/// <summary>
/// Helps to hide UIView and remove blank space occupied by invisible view
/// </summary>
public class HidingViewHolder
{
    private readonly UIView view;
    private readonly NSLayoutConstraint heightConstraint;
    private nfloat viewHeight;

    public HidingViewHolder(UIView view, string heightConstraintId)
    {
        this.view = view;
        this.heightConstraint = view
            .GetConstraintsAffectingLayout(UILayoutConstraintAxis.Vertical)
            .SingleOrDefault(x => heightConstraintId == x.GetIdentifier());
        this.viewHeight = heightConstraint != null ? heightConstraint.Constant : 0;
    }

    public void ShowView()
    {
        if (!view.Hidden)
        {
            return;
        }
        if (heightConstraint != null)
        {
            heightConstraint.Active = true;
            heightConstraint.Constant = viewHeight;
        }
        view.Hidden = false;
    }

    public void HideView()
    {
        if (view.Hidden)
        {
            return;
        }
        if (heightConstraint != null)
        {
            viewHeight = heightConstraint.Constant;
            heightConstraint.Active = true;
            heightConstraint.Constant = 0;
        }
        view.Hidden = true;
    }
}
like image 151
artplastika Avatar answered Nov 01 '22 11:11

artplastika