본문 바로가기

Develop/MAUI 가이드

[Xamarin] 플랫폼 종속 코드 작성하는 방법

반응형

플랫폼 종속 코드
Platform-Specific Code

플랫폼에 종속적인 코드 작성하는 방법

Xamarin 은 플랫폼에 독립적인 UI를 만들 수 있도록 도와주기는 하지만, 플랫폼 별로 다른 이미지나 코드를 적용해야 하는 순간이 있습니다. 이때 플랫폼 별로 다른 값을 적용할 수 있는 방법을 알려드리도록 하겠습니다.

플랫폼 별 Code

if (Device.RuntimePlatform == Device.iOS)
{
    Padding = new Thickness(0, 20, 0, 0);
}

Devce.RuntimePlatform 을 활용해서 플랫폼 별로 다른 코드를 실행시킬 수 있습니다. Device 가 구분할 수 있는 플랫폼은 아래 목록과 같습니다.

  • Device.Android
  • Device.iOS
  • Device.macOS
  • Device.WPF
  • Device.UWP
  • Device.GTK
  • Deivce.Tizen

플랫폼 별 Compile

.NET 에서 기본으로 제공하는 Conditional Compilation 을 활용해서 플랫폼 별로 다른 코드를 컴파일합니다.

#if __MOBILE__
// Android && iOS
#endif
#if __IOS__
// iOS
#endif
#if __ANDROID__
// Android
#endif
#if __ANDROID_11__
// Android API 11 이상
#endif
#if WINDOWS_UWP
// UWP
#endif
#if __MACOS__
// macOS-specific code
#endif

플랫폼 별 XAML

<ToolbarItem Text="edit" Order="Primary">
    <ToolbarItem.Icon>
        <OnPlatform x:TypeArguments="FileImageSource">
            <On Platform="iOS" Value="edit.png" />
            <On Platform="Android" Value="ic_action_edit.png" />
            <On Platform="UWP" Value="Images/edit.png" />
        </OnPlatform>
    </ToolbarItem.Icon>
</ToolbarItem>

OnPlatform 태그를 사용해서 XAML 내에서도 플랫폼에 종속적인 XAML을 작성할 수 있습니다.

OnPlatform 은 Generic Class 라 x:TypeArguments 로 대상이 될 속성의 클래스를 지정해주어야 합니다.

<Button Margin="0,10,0,0"
        Text="Learn more"
        Command="{Binding OpenWebCommand}"
        BackgroundColor="{OnPlatform Android=Blue, iOS=Orange}" />

위 예제와 같이 한줄에 간단하게 작성할 수도 있습니다.

반응형