Restrict orientation of view controller when using

2019-08-16 08:43发布

I've set up a static UITableView with iOS Designer (IB in Objective-C world). But the orientation is changed despite I want to restrict it.

I've done the following:

In Properties under Simulated Metrics I chose Portrait as Orientation. Than I'm implementing the following functions for my UITableViewController:

public override bool ShouldAutorotate ()
{
    return false;
}

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations ()
{
    return UIInterfaceOrientationMask.Portrait;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation ()
{
    return UIInterfaceOrientation.Portrait;
}

GetSupportedInterfaceOrientations is called and I return Portrait but the view is still rotated. What I'm missing?

Edit:

I've used the approach discussed in View Orientation. This works for my view controllers. The static UITableViewController is pushed in this way on the stack:

this.PresentViewController (new UINavigationController(myStaticTableViewController), true, null);

Here the standard implementation of UINavigationController is used. I also tried it with my CustomNavigationController which implements

partial class CustomNavigationController : UINavigationController
{

    public CustomNavigationController (IntPtr handle) : base (handle)
    {
    }

    public override bool ShouldAutorotate ()
    {
        return TopViewController.ShouldAutorotate();
    }

    public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation ()
    {
        return TopViewController.PreferredInterfaceOrientationForPresentation ();
    }
}

but I can't do something like this

this.PresentViewController (new CustomNavigationController(myStaticTableViewController), true, null);

because it cannot convert my table view controller to IntPtr. Perhaps that's the reason why it doesn't respect the interface orientation. What solutions do I have?

1条回答
你好瞎i
2楼-- · 2019-08-16 09:19

Seems that I only had to add another constructor as stated in the linked thread. Now my CustoMNavigationController looks like this:

partial class CustomNavigationController : UINavigationController
{

    public CustomNavigationController(UIViewController rootViewController) : base(rootViewController)
    {

    }

    public CustomNavigationController (IntPtr handle) : base (handle)
    {
    }

    public override bool ShouldAutorotate ()
    {
        return TopViewController.ShouldAutorotate();
    }

    public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation ()
    {
        return TopViewController.PreferredInterfaceOrientationForPresentation ();
    }
}

Now I can use

this.PresentViewController (new CustomNavigationController(myStaticTableViewController), true, null)

and everything works as expected.

查看更多
登录 后发表回答