DEV
DEV

Reputation: 949

How to use Segmented Control in Multiplatform App in Xamarin.Forms

Here is so far what i tried. I am trying to load it programmatically.I am writing this code in the multi-platform project. As shown in the image attached.

Img here.

enter image description here

var layout = new StackLayout()
{
    Orientation = StackOrientation.Vertical,
    Spacing = 20,
    Padding = new Thickness(0, 20, 0, 0)
};

if (Device.OS == TargetPlatform.iOS)
{
    var segmentControl = new UISegmentedControl();
    segmentControl.Frame = new CGRect(20, 20, 280, 40);
    segmentControl.InsertSegment("One", 0, false);
    segmentControl.InsertSegment("Two", 1, false);
    segmentControl.SelectedSegment = 1;
    segmentControl.ValueChanged += async (sender, e) =>
    {
        var selectedSegmentId = (sender as UISegmentedControl).SelectedSegment;
        await MainPage.DisplayAlert($"Native Segmented Control Clicked {selectedSegmentId}",
                                                  "Whoa!!!!!!", "OK");
    };
    layout.Children.Add(segmentControl);
}

Is it possible to do like this? Or custom render is the only solution?

Upvotes: 2

Views: 1803

Answers (1)

Alex Sorokoletov
Alex Sorokoletov

Reputation: 3101

It is possible to use SegmentedControl in iOS app written with Xamarin.Forms.

The code that you are asking about will be a good fit if you will use shared project approach with Xamarin.Forms.

In that case you need to wrap iOS-specific code in conditional directive #if __IOS__ (#if __ANDROID__ for Android-specific code)

var layout = new StackLayout()
{
    Orientation = StackOrientation.Vertical,
    Spacing = 20,
    Padding = new Thickness(0, 20, 0, 0)
};

#if __IOS__
if (Device.OS == TargetPlatform.iOS)
{
    var segmentControl = new UISegmentedControl();
    segmentControl.Frame = new CGRect(20, 20, 280, 40);
    segmentControl.InsertSegment("One", 0, false);
    segmentControl.InsertSegment("Two", 1, false);
    segmentControl.SelectedSegment = 1;
    segmentControl.ValueChanged += async (sender, e) =>
    {
        var selectedSegmentId = (sender as UISegmentedControl).SelectedSegment;
        await MainPage.DisplayAlert($"Native Segmented Control Clicked {selectedSegmentId}",
                                                  "Whoa!!!!!!", "OK");
    };
    layout.Children.Add(segmentControl);
}
#endif

There is a good example showing how to use UISegmentedControl with Xamarin.Forms from James Montemagno Embedding Native Controls into Xamarin.Forms

However, it looks like you have you solution based on PCL approach.

When using Portable Class Library approach with Xamarin.Forms, you will have to create a custom control (check this simple example about UISegmentedControl) or use 3rd party controls like SegmentedControl.FormsPlugin

Upvotes: 3

Related Questions