Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set ContentPage orientation or screen orientation on particular page in Xamarin.Forms cross platform

How to set Content-Page orientation or screen orientation on particular page in Xamarin.Forms cross platform.

I have set ScreenOrientation = ScreenOrientation.

Portrait at property of all platform but I want to show some page show in both variation means Portrait and Landscape, so how to set on page in `xamarin.forms.

set screen orientation not device wise but set on page-wise some pages show in Landscape & some page show in Portrait in xamarin forms cross- platform

like image 259
sonu Avatar asked Jan 05 '23 12:01

sonu


1 Answers

You can do this by creating a dependency using DependencyService for specific platforms.

Try doing this:

Interface

public interface IOrientationService
    {
        void Landscape();
        void Portrait();
    }

For Android:

[assembly: Xamarin.Forms.Dependency(typeof(OrientationService))]
namespace Orientation
{
    public class OrientationService: IOrientationService
    {
        public void Landscape()
        {
            ((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Landscape;
        }

        public void portrait()
        {
            ((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
        }
    }
}

For iOS:

[assembly: Xamarin.Forms.Dependency(typeof(OrientationService))]
namespace Orientation
{
    public class OrientationService: IOrientationService
    {
        public void Landscape()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
        }

        public void Portrait()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
        }
    }
}

Then you can use it like this

DependencyService.Get<IOrientationService>().Landscape();
DependencyService.Get<IOrientationService>().Portrait();

Hope it helps!

like image 109
mindOfAi Avatar answered Jan 13 '23 18:01

mindOfAi