I experience an unexpected behavior when attempting to assign constraints dynamically in a single view controller based on device orientation.
Desired behavior: As shown in the code below I am using VFL to attach a view to the right, top and left edges of the superview with a height of 300 of when in portrait mode and then switch to having the same view attached to the left and top edge with a height of 90 and width of 160 when in landscape mode.
if (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown)
{
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[green(300)]", 0, metrics, views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[green]|", 0, new NSDictionary(), views));
}
else
{
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[green(90)]", 0, metrics, views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[green(160)]", 0, metrics, views));
}
Experienced Behavior: We are instead seeing the desired behavior for the portrait mode on the initial load of the view and also when turned to landscape mode. However, when turing back to portrait mode the view control disappears each time thereafter when the device is turned to portent mode but landscape mode continues to function. In short portrait mode only works the first time.
I've done quite extensive research and could not identify the problem. I would be very appreciative of any insight towards a solution.
Here is the complete code just in case:
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System;
using System.CodeDom.Compiler;
namespace iOS.UI
{
partial class TestConstraintsController : UIViewController
{
public TestConstraintsController (IntPtr handle) : base (handle)
{
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
AdjustGeometry ();
}
public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate (fromInterfaceOrientation);
AdjustGeometry ();
}
public void AdjustGeometry()
{
UIInterfaceOrientation orientation = UIApplication.SharedApplication.StatusBarOrientation;
NSDictionary views = NSDictionary.FromObjectsAndKeys (
new NSObject[] { greenBox },
new NSObject[] { new NSString ("green") }
);
View.RemoveConstraints (View.Constraints);
if (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown)
{
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[green(boxHeightPortrait)]", 0, new NSDictionary(), views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[green]|", 0, new NSDictionary(), views));
}
else
{
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[green(90)]", 0, new NSDictionary(), views));
View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[green(160)]", 0, new NSDictionary(), views));
}
}
}
}