Skip to content

Instantly share code, notes, and snippets.

@BrunoVT1992
Created September 18, 2017 13:27
Show Gist options
  • Save BrunoVT1992/f2d93f3db8924a41c979fc02f0610dcb to your computer and use it in GitHub Desktop.
Save BrunoVT1992/f2d93f3db8924a41c979fc02f0610dcb to your computer and use it in GitHub Desktop.
StackView for Xamarin.iOS without the need for AutoLayout constraints
using System;
using System.Linq;
using CoreGraphics;
using UIKit;
namespace iOS
{
public class StackView : UIView
{
nfloat _previousWidth;
nfloat _previousHeight;
public event EventHandler SizeChanged;
bool _autoAdaptSize;
public bool AutoAdaptSize
{
get
{
return _autoAdaptSize;
}
set
{
_autoAdaptSize = value;
SetNeedsLayout();
}
}
StackOrientation _orientation;
public StackOrientation Orientation
{
get
{
return _orientation;
}
set
{
_orientation = value;
SetNeedsLayout();
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
PositionSubviews();
if (_previousWidth != Bounds.Width || _previousHeight != Bounds.Height)
{
_previousWidth = Bounds.Width;
_previousHeight = Bounds.Height;
SizeChanged?.Invoke(this, EventArgs.Empty);
}
}
void PositionSubviews()
{
if (Subviews?.Any() == true)
{
var pos = 0.0;
foreach (var v in Subviews)
{
if (Orientation == StackOrientation.Horizontal)
{
v.Frame = new CGRect(pos, v.Frame.Y, v.Frame.Width, v.Frame.Height);
pos += v.Frame.Width;
}
else
{
v.Frame = new CGRect(v.Frame.X, pos, v.Frame.Width, v.Frame.Height);
pos += v.Frame.Height;
}
}
if (AutoAdaptSize)
{
if (Orientation == StackOrientation.Horizontal)
{
Frame = new CGRect(Frame.X, Frame.Y, pos, Frame.Height);
}
else
{
Frame = new CGRect(Frame.X, Frame.Y, Frame.Width, pos);
}
}
}
else if (AutoAdaptSize)
{
Frame = new CGRect(Frame.X, Frame.Y, 0, 0);
}
}
public override void AddSubview(UIView view)
{
base.AddSubview(view);
SetNeedsLayout();
}
public enum StackOrientation
{
Horizontal, Vertical
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment