0

I'm trying to follow the UIScrollView And Autolayout Mixed approach.

I've seen other similar questions but with no accepted answer.

I'm not sure that this is what I need.

Please understand that I'm neither working with Storyboards nor XIBs. All my views are created programmatically using c# in Xamarin.iOS. This is very similar to objective C code.

Like many others I can't find a way to have my scroll view to actually scroll.

So in my main View Controller I have the following in ViewDidLoad():

   public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        _scrollView = new UIScrollView
        {
            ShowsHorizontalScrollIndicator = false,
            TranslatesAutoresizingMaskIntoConstraints = false,
            AlwaysBounceVertical = true,
            Bounces = true
        };

        _refreshControl = new UIRefreshControl { TranslatesAutoresizingMaskIntoConstraints = false };
        _refreshControl.Enabled = true;
        _refreshControl.ValueChanged -= RefreshControl_ValueChanged;
        _refreshControl.ValueChanged += RefreshControl_ValueChanged;
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            _scrollView.RefreshControl = _refreshControl;
        }
        else
        {
            _scrollView.AddSubview(_refreshControl);
        }

        this.View.AddSubview(_scrollView);

        _scrollViewContainer = new UIView { TranslatesAutoresizingMaskIntoConstraints = true };
        _scrollView.AddSubview(_scrollViewContainer);

        _scrollView.Anchor(top: this.View.SaferAreaLayoutGuide().TopAnchor, leading: this.View.LeadingAnchor, bottom: this.View.SaferAreaLayoutGuide().BottomAnchor, trailing: this.View.TrailingAnchor);
    }

Nothing really fancy, I create my UIScrollView add it as a sub view of the main View. Create a UIRefreshControl and add it to the scroll view. Create and add a plain UIView to the UIScrollView in order to put all my subviews.

Because I'm using AutoLayout the ScrollView is anchored within constraints of the main view.

Now later in ViewWillAppear(), I'm creating Card Views that are added to the plain UIView. These card views are using autoloayout to be stacked on top of each other, the first card is anchored to the container view's top, leading and trailing anchors.

Everything in these cards is using autolayout, to basically stack everything.

        public UIView BuildQOLCard()
        {
            CardView qolCard = new CardView();
            _scrollViewContainer.AddSubview(qolCard);
            qolCard.TranslatesAutoresizingMaskIntoConstraints = false;
            qolCard.CornerRadius = 5f;
            qolCard.ShadowOffsetHeight = 0;
            qolCard.ShadowOffsetWidth = 0;
            qolCard.BackgroundColor = UIColor.White;
...
           qolCard.Anchor(leading: _scrollViewContainer.LeadingAnchor, trailing: _scrollViewContainer.TrailingAnchor, top: _scrollViewContainer.TopAnchor, padding: new UIEdgeInsets(10f, 10f, 10f, 10f));

            return qolCard;
        }

Of course the container view won't magically know how to size itself. So I'll have to give it a size otherwise I won't see anything.

So I mage a helper like this:

public void SizeScrollViewContentSize()
{
    nfloat scrollViewHeight = 0.0f;
    foreach (UIView view in this._scrollViewContainer.Subviews)
    {
        scrollViewHeight += view.Frame.Size.Height;
    }

    this._scrollViewContainer.Frame = new CGRect(0, 0, this._scrollView.Frame.Width, scrollViewHeight);
}

But I can't seem to figure out when to call it because the subviews are here but their sizes are unknown. I tried calling it from ViewDidLayoutSubviews().

Any help appreciated.


EDIT : Applying te recommandations of the accepted answer, led to scrolling being enabled but the scroll view always bounces back to top.

Here is the code right now:

public override void ViewDidLoad()
{
    base.ViewDidLoad();

    _scrollView = new UIScrollView
    {
        ShowsHorizontalScrollIndicator = false,
        TranslatesAutoresizingMaskIntoConstraints = false
    };

    if (!UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
    {
        _scrollView.AlwaysBounceVertical = true;
        _scrollView.Bounces = true;
    }

    _refreshControl = new UIRefreshControl { TranslatesAutoresizingMaskIntoConstraints = false };
    _refreshControl.Enabled = true;
    _refreshControl.ValueChanged -= RefreshControl_ValueChanged;
    _refreshControl.ValueChanged += RefreshControl_ValueChanged;
    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
    {
        _scrollView.RefreshControl = _refreshControl;
    }
    else
    {
        _scrollView.AddSubview(_refreshControl);
    }

    this.View.AddSubview(_scrollView);

    _scrollViewContainer = new UIView { TranslatesAutoresizingMaskIntoConstraints = false };
    _scrollView.AddSubview(_scrollViewContainer);

    _scrollView.Anchor(top: this.View.SaferAreaLayoutGuide().TopAnchor, leading: this.View.LeadingAnchor, bottom: this.View.SaferAreaLayoutGuide().BottomAnchor, trailing: this.View.TrailingAnchor);

    // Only define the width of the container
    _scrollViewContainer.TopAnchor.ConstraintEqualTo(_scrollView.TopAnchor).Active = true;
    _scrollViewContainer.LeadingAnchor.ConstraintEqualTo(_scrollView.LeadingAnchor).Active = true;
    _scrollViewContainer.WidthAnchor.ConstraintEqualTo(_scrollView.WidthAnchor).Active = true;
}

Card one:

            CardView qolCard = new CardView();
            _scrollViewContainer.AddSubview(qolCard);
            qolCard.TranslatesAutoresizingMaskIntoConstraints = false;
            qolCard.CornerRadius = 5f;
            qolCard.ShadowOffsetHeight = 0;
            qolCard.ShadowOffsetWidth = 0;
            qolCard.BackgroundColor = UIColor.White;
...
           qolCard.Anchor(leading: _scrollViewContainer.LeadingAnchor, trailing: _scrollViewContainer.TrailingAnchor, top: _scrollViewContainer.TopAnchor, padding: new UIEdgeInsets(10f, 10f, 10f, 10f));

card 2:

               CardView goalsCard = new CardView();
                _scrollViewContainer.AddSubview(goalsCard);
                goalsCard.TranslatesAutoresizingMaskIntoConstraints = false;
                goalsCard.CornerRadius = 5f;
                goalsCard.ShadowOffsetHeight = 0;
                goalsCard.ShadowOffsetWidth = 0;
                goalsCard.BackgroundColor = UIColor.White;
...
               // Top should be constrained to the previous CardView's Bottom
                goalsCard.Anchor(leading: _scrollViewContainer.LeadingAnchor, trailing: _scrollViewContainer.TrailingAnchor, top: qolCard.BottomAnchor,padding: new UIEdgeInsets(10f, 10f, 10f, 10f));

Final anchor:

           // constraint the last card bottom to the bottom of the scrollview container
            goalsCard.Anchor(bottom: context._scrollViewContainer.BottomAnchor);

The Anchor Helper:

   internal static void Anchor(this UIView uIView, NSLayoutYAxisAnchor top = null, NSLayoutXAxisAnchor leading = null, NSLayoutYAxisAnchor bottom = null, NSLayoutXAxisAnchor trailing = null, UIEdgeInsets padding = default, CGSize size = default)
    {
        uIView.TranslatesAutoresizingMaskIntoConstraints = false;
        if (top != null)
        {
            uIView.TopAnchor.ConstraintEqualTo(top, padding.Top).Active = true;
        }

        if (leading != null)
        {
            uIView.LeadingAnchor.ConstraintEqualTo(leading, padding.Left).Active = true;
        }

        if (bottom != null)
        {
            uIView.BottomAnchor.ConstraintEqualTo(bottom, -padding.Bottom).Active = true;
        }

        if (trailing != null)
        {
            uIView.TrailingAnchor.ConstraintEqualTo(trailing, -padding.Right).Active = true;
        }

        if (size.Width != 0)
        {
            uIView.WidthAnchor.ConstraintEqualTo(size.Width).Active = true;
        }

        if (size.Height != 0)
        {
            uIView.HeightAnchor.ConstraintEqualTo(size.Height).Active = true;
        }
    }

1 Answer 1

1

A scroll view needs its Frame defined and it needs its Content defined. If the content is constrained properly, scrolling is automatic.

I'll go through this step-by-step - using Storyboard just so we can see what's happening. Absolutely no different when we do it through code.

Start with a View Controller, add a scroll view, and constrain it to all four sides (I gave it a green background so we can see it):

enter image description here

Now we add a "container" view (cyan background), and constrain all 4 sides to the scroll view:

enter image description here

If we run this, we see:

enter image description here

That's because the "container" has no width or height. Its Leading / Trailing / Top / Bottom constraints are defining the scroll view's content.

So, let's constrain it Equal Width and Equal Height to the scroll view:

enter image description here

run it, and we see this:

enter image description here

Which is fine, except... it will never scroll, because it is the same height as the scroll view.

So, I delete the Equal Height - because I want the container's content to determine its height.

I add a "CardView" and set its Top / Leading / Trailing constraints to Top / Leading / trailing of "container", with 10-pts "padding" and a Height of 100. I also give it a Bottom Constraint to the Bottom of "container" (+10) - which will "pull the bottom of the container" up to 10-pts below the bottom of the CardView:

enter image description here

resulting in:

enter image description here

Now I add a second CardView, constrain Leading / Trailing constraints to Leading / trailing of container, with 10-pts "padding" and a Height of 100. And I set its Top constraint to the Bottom of CardView-1 (+10), and I constrain its Bottom to the Bottom of "container" (+10):

enter image description here

Unfortunately, we now have a 10-pt constraint from Bottom of CardView-1 and a 10-pt constraint from Bottom of CardView-2 - which, of course, won't work.

So, let's delete the "Bottom to Superview" constraint from CardView-1

enter image description here

and we get this:

enter image description here

Let's repeat those steps for a few more card views, each time constraining Leading / Trailing to "container", Height of 100, Top to Bottom of previous CardView... and then constrain only the Bottom of the last CardView to the Bottom of "container":

enter image description here

and Yay! We can scroll:

enter image description here

Doing this via code is just a matter of remembering that each CardView's Top should be constrained to the previous CardView's Bottom -- except for the first card, which you constrain to the Top of "container" and the last card, which you constrain to the Bottom of "container".

All done with auto-layout. No need to do any "calculate height and set frame" code.


As a side note, you can use a StackView and get rid of most of that:

  • forget the "container"
  • add a stack view to the scroll view
    • axis: vertical, spacing: 10
  • constrain all 4 sides of the stack view to the scroll view with 10-pts padding
  • give the stack view a Width constraint equal to scroll view width -20 (for the 10-pts padding on each side)

Then, just add your CardViews as arrangedSubviews of the stack view.

And.... Done!

6
  • Thanks for the great explanation.
    – anon
    May 1, 2020 at 9:21
  • Just a quick update to let you know that it scrolls but it always bounces back to top. What could be the problem?
    – anon
    May 1, 2020 at 15:03
  • @OlivierMATROT - you'd have to show me the code you are using in order to figure out why.
    – DonMag
    May 1, 2020 at 15:35
  • @OlivierMATROT - could be a couple things... Are you adding a new "card" each time you pull-to-refresh? If so, are you removing the previous card's bottom anchor when you add a bottom anchor to the newly added card? Also, when the refresh control ends refreshing, it scrolls the content back to the top... I don't use Xamarin / C#, so I can't give you a complete example (I could give you one in either Swift or Objective-C)
    – DonMag
    May 1, 2020 at 16:38
  • When I pull to refresh, I remove all the subviews (cards) from the scrollViewContainer and add them back with updated data. The problem is I can't even scroll up to the bottom of the 2nd card on a small screen like the iPhone 4s. It bounces back to top as soon as I release the gesture to scroll down. The pull to refresh pat seems ok to me. It is really a matter about being able to scroll up. Hope that helps.
    – anon
    May 1, 2020 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.