Skip to content

Instantly share code, notes, and snippets.

@lothrop
Last active September 23, 2020 12:12
Show Gist options
  • Save lothrop/95e64d5dddbd5dd14072 to your computer and use it in GitHub Desktop.
Save lothrop/95e64d5dddbd5dd14072 to your computer and use it in GitHub Desktop.
private UIScrollView _scrollView;
private UIView _contentView;
public override void ViewDidLoad()
{
base.ViewDidLoad();
_scrollView = new UIScrollView
{
ShowsHorizontalScrollIndicator = false,
TranslatesAutoresizingMaskIntoConstraints = false
};
_contentView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false };
var subviews = View.Subviews.ToArray();
var constraints = View.Constraints.Select(constraint => NSLayoutConstraint.Create(
constraint.FirstItem == View ? _contentView : constraint.FirstItem,
constraint.FirstAttribute,
constraint.Relation,
constraint.SecondItem == View ? _contentView : constraint.SecondItem,
constraint.SecondAttribute,
constraint.Multiplier,
constraint.Constant)).ToArray();
View.RemoveConstraints(View.Constraints);
Array.ForEach(subviews, view => view.RemoveFromSuperview());
_contentView.AddSubviews(subviews);
_scrollView.Add(_contentView);
_contentView.AddConstraints(constraints);
Add(_scrollView);
var edges = new[]
{
NSLayoutAttribute.Top,
NSLayoutAttribute.Bottom,
NSLayoutAttribute.Left,
NSLayoutAttribute.Right
};
View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Width, NSLayoutRelation.Equal,
_contentView, NSLayoutAttribute.Width, 1, 0));
_scrollView.AddConstraints(
edges.Select(
edge => NSLayoutConstraint.Create(_scrollView, edge, NSLayoutRelation.Equal, _contentView, edge, 1, 0))
.ToArray());
View.AddConstraints(
edges.Select(
edge => NSLayoutConstraint.Create(View, edge, NSLayoutRelation.Equal, _scrollView, edge, 1, 0))
.ToArray());
}
@omatrot
Copy link

omatrot commented Apr 26, 2020

Hi there.
I know that this is an old gist.
I'd like to use your code in an app where I'm creating UI elements programmatically. I presume this code should be called when all other UI elements have been added to the view right ? If I were to use a base class with it, what would come to mind about thinks I should be aware of?
Thanks in advance.

@lothrop
Copy link
Author

lothrop commented Sep 23, 2020

Sorry I missed this notification. This code will take the views that are currently in your ViewController and move them into a ScrollView. So yes, add the elements first. Should work as a base class, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment