简体   繁体   中英

Center Vertically UIStackView inside UIScrollView with scroll

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.

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.

[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

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