1

Hello it's been imposible to center a UIStackView inside a ScrollView having scroll working ...

I've tried lot of things but the best one has been this:

   stackView = new UIStackView
            {
                Axis = UILayoutConstraintAxis.Vertical,
                Alignment = UIStackViewAlignment.Center,
            };

            scroll = new UIScrollView() { };

            Add(scroll);

            scroll.AddSubview(stackView);

            scroll.EnableAutoLayout();

            scroll.FullSizeOf(View);



            stackView.AddArrangedSubview(logo);
            stackView.AddArrangedSubview(_activityIndicatorView);

//... more items

logo.HeightAnchor.ConstraintEqualTo(72).Active = true;

            enterpriseCodeField.HeightAnchor.ConstraintEqualTo(50).Active = true;
            enterpriseCodeField.WidthAnchor.ConstraintEqualTo(0.65f * View.Frame.Size.Width).Active = true;

//... more items 

 stackView.SetCustomSpacing(35, logo);
            stackView.SetCustomSpacing(35, _activityIndicatorView);

//... more items

            View.AddConstraint(NSLayoutConstraint.Create(stackView, NSLayoutAttribute.CenterY, 0, scroll, NSLayoutAttribute.CenterY, 1, 0));
            View.AddConstraint(NSLayoutConstraint.Create(stackView, NSLayoutAttribute.CenterX, 0, scroll, NSLayoutAttribute.CenterX, 1, 0));

This method scroll.EnableAutoLayout(); is to: TranslatesAutoresizingMaskIntoConstraints = false;

This method scroll.FullSizeOf(View); is to : set leading trailing top etc...

Anyone can help me please ? what I'm doing wrong ? In android it's very easy to achieve this behavior ...

Thank you so much.

Saveen
  • 4,120
  • 14
  • 38
  • 41
CarLoOSX
  • 505
  • 3
  • 9

2 Answers2

0

You can use the scrollview centerX anchor constraint. This way you set the centerX anchor constraint of the scroll view to be the same as the scrollView.

Otto Gutierrez
  • 447
  • 2
  • 5
  • 15
  • It's the same behavior as View.AddConstraint(NSLayoutConstraint.Create(stackView, NSLayoutAttribute.CenterY, 0, scroll, NSLayoutAttribute.CenterY, 1, 0)); the problem is that if I center the stack then I 'don't have the scroll working I also tried this public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); scroll.ContentSize = new CGSize(stackView.Frame.Width, stackView.Frame.Height); } Any idea ? – CarLoOSX Mar 15 '18 at 14:15
  • hey @CarLoOSX, are you setting the contentSize of the scrollView? – Otto Gutierrez Mar 16 '18 at 14:17
0

[Updated link] I uploaded a project with some code achieving what you are looking for. Please check it out here -> ScrollViewTest

The link should work now

Otto Gutierrez
  • 447
  • 2
  • 5
  • 15
  • Hey @Otto thanks for your answer.Yes I set the scrollview contentsize to be equal as the stackview content. Github shows me 404 not found. If you can, here’s my email:carlos.mlpz@gmail.com .Thank you so much. – CarLoOSX Mar 17 '18 at 12:34