자마린과 React Native 의 차이가 궁금하다면.. 여기로...
https://www.mobileappdaily.com/2018/08/7/xamarin-vs-react-native/amp




Two of the popular cross-platform frameworks includes React Native and Xamarin. The year 2018 was stellar concerning apps that were produced in any defined year and most of these applications were developed using these two influential cross-platform mobile app development frameworks.

iOS applications have always used Objective-C and Swift programming language whereas, for Android the programming language is Java. And, if we talk about the trend in the modern app development domain, it is shifting greatly with the introduction of new and innovative tools.

For your better understanding of Xamarin and React Native, we have stricken a fair comparison titled ‘Xamarin Vs React Native’ which highlight the significant differences between the two frameworks.

About Xamarin

Xamarin is a cross-platform framework for the implementations of the Common Language Infrastructures. It came into the market in 2011 and was acquired by Microsoft in 2016. Xamarin has an armory of tools that can be handy for developers to build cross-platform mobile apps.

Xamarin app development framework lets the developer create Android and iOS apps with Xamarin tools which can be downloaded with Visual Studio. Due to its excellent functionalities, Xamarin is deployed by more than 15,000 companies.

About React Native

React Native is a JavaScript framework for developing mobile apps for iOS and Android. React native is based on React which itself is a Facebook’s JavaScript library for crafting UIs. But it targets mobile platforms and not browsers.

To put it simply, the developers can develop mobile apps with full look and feel of “native.” The best part of React Native app development framework is that due to its code-sharing ease, an app can be simultaneously developed for both Android and iOS.

React Native Vs Xamarin

Xamarin Vs React Native: Comparison

Below are some crucial factors on which, we will proceed to compare react native and Xamarin frameworks:

1. React Native vs Xamarin: Usage

a. Use of React Native

Now let’s talk about the uses of React Native framework, as it works on the modern one-way data flow. This app development framework is productive in a marginal way. Recently, some changes have been brought to the framework, particularly in the JS development ecosystem. And thus if you are someone who loves Java then you are sure to love this too.

b. Use of Xamarin

Xamarin also provides great offerings for the application developers and programmers who work on ASP.NET MVC, Web Forms, or other MVC platforms. This language works exceptionally well on the prescribed platforms and thus a number of developers like to work with this particular framework the most.

Another offering for the developers is that the Xamarin framework offers functionality to integrate well within the MVVM a.k.a. ‘Model–View–Viewmodel’ framework style.

Verdict: Owing to the functionality factor that both of these frameworks offer, this has to be a tie between the two.

React vs Xamarin

2. React Native vs Xamarin: Development platforms

a. React Native Development Environment

The best thing about the components of React Native is that they offer Integrated Development Environment which is also known as IDE to the developers. The developers can then also use Expo to debug and develop a React Native application. Hot loading is another great feature that developers can use while working with this development framework.

b. Xamarin Development Environment

Xamarin is powerful in this context because here the developers can write their code for an iPhone app even on Windows and then compile the same for Mac. And that makes it the best choice for the app developers.

However, programmers/developers would need a platform that they would utilize for the built. And this process is actually quite powerful for that.

Verdict: Depending upon the functionality, we declare Xamarin as the winner here.

3. React Native vs Xamarin: Community Support

a. React Native Community Assistance

A fair comparison of React Native with other frameworks shows it is relatively young and needs to go long way before making its position prominent in the industry. Interestingly, a wide collaboration among developers across the globe has made it possible to rank react Native in one of the best JavaScript frameworks available in the market.

However, the community support of developers is there for the language but is not as extensive as the support available for other programming languages.

b. Xamarin Community Assistance

If we talk about the support, this cross-platform framework has got great support from the community forums. Xamarin is used by companies like Coca-Cola and Gummy Drop. Moreover, there are additional sources like Stack Overflow that offers huge support to Xamarin. While working with the programming language a developer can find great information from the different sources.

With the availability of Xamarin Forms, the developers can share visual elements and part of the codebase, it in turns, helps the overall Xamarin community with a lot of tips, tools, and data.

Verdict: Owing to the functionality, Xamarin is declared the winner.

Xamarin vs React Native

4. React Native vs Xamarin: Ready-Made Components

a. React Native Components

React Native does offer ready-made codes, but there are chances that the codes which are available today can have a better version in the near future and nobody wants their app to get outdated so soon. So, it makes more sense, if the developer defines the components in the first go, which he wants to embed in the React Native app.

Still, if the developer is willing to use the code, he must update it once the better version arrives or the codes can be replaced altogether; thanks to React Native’s component-level modularity.

b. Xamarin Components

Sometimes, the Xamarin codes can be complex, but there is a high probability that a developer can find similar codes related to their projects, especially when if someone is searching for coding buttons with very specific characteristics. For the community assistance, Xamarin team themselves share various ready-made components and codes at regular intervals of time, which further aid the developers to come up with beautiful and functional apps.

Verdict: Due to the ease of codes usability, Xamarin scores over React Native

5. React Native vs Xamarin: Code Deployment and App Performance

In general, there is not much difference in the app performance developed using React Native and Xamarin. Still, if you wish to know the difference, we have to deep dive into the technical aspects of performance and deployment.

Here are some of the concepts that you need to consider:

  • 64-bits support: It’s a universal fact that an architecture based on 64-bit code performs better than 32-bit code. And, React Native doesn’t support 64-bits Android apps, which of course is a downside for it. On the other hand, Xamarin easily supports 64-bit architectures.
  • JIT and AOT: React Native and Xamarin are not compiled to native. In React Native, Javascript is interpreted during compilation, whereas, .NET language is compiled to binary code in Xamarin.
  • Just in Time (JIT) compilation: It compiles bytecode into native at runtime. In React Native, JavaScriptCore can be deployed to interpret Javascript for iOS and Android apps.
  • Ahead of time (AOT) compilation: As the name suggests, all the codes are compiled well before the processing of the app. It can be used in Xamarin for both iOS and Android apps, but React native clearly lacks here.

Xamarin vs React Native

a. React Native Code Deployment and App Performance

React Native uses JavaScript coding but on an internal level, the framework uses the same fundamental UI blocks as any other Android or iOS applications. JavaScriptCore can also be used on the Android platform but it prevents the JIT (Just in Time) compilation that is being used on Android.

b. Xamarin Code Deployment and App Performance

Talking about Xamarin, this cross-platform framework uses C# along with using JIT compilation and AOT (ahead of time) compilation. Owing to the fact that iOS prevents the JIT compilation, Xamarin AOT is used to compile the application. The platform takes JIT as the default compilation but it can also be configured to Ahead of Time compilation.

Verdict: This fair comparison makes us declare Xamarin framework as the winner in the compilation race.

6. React Native vs Xamarin: Compilation Time and Development Speed

a. React Native Compilation Time and Development Speed

React Native scripted and hence, it’s quite effective. It adds more value to the app, as when the process seems to slow down, we can reload the Javascript, and thus the can be tested and modified quickly. Interestingly, React Native apps and web apps can be debugged in a similar manner. The Chrome developer tool can be deployed to debug the app where ever it’s needed.

b. Xamarin Compilation Time and Development Speed

With time, the compilation of Xamarin apps increases and if there is some bigger project, more time is required for the compilation. And all these factors can directly impact the project time and cost. To bypass this, the developers can go for the Gorilla option, which allows faster Preview of the UI while coding.

Verdict: React Native

Xamarin vs React Native

7. React Native vs Xamarin: App Testing

a. React Native Testing Tools

With the right set of tools in hand, testing React Native components is quite simple. For static type testing, React Native has a tool called PropTypes, which requires almost no setup. The unit and integration testing in React Native can be done with the help of test runner and an assertion library which comes in the form of Jest, a javascript testing framework with rich API for behavior and spec tests

b. Xamarin Testing Tools

Testing tools like NUnit and Xamarin Test Recorder can be used to test cross-platform UIs. Both of these tools let the developer create the test which they wish to execute. For wider ranges of devices, Xamarin Test Cloud can be brought into play.

Verdict: Both React Native and Xamarin are on the same page regarding the testing tools.

8. React Native vs Xamarin: Designing Aspects

a. React Native Designing Aspects

UI remains one of the significant factors while developing an app, as the developer devotes much of the time during the UI designing. Regarding UI, React Native is similar to Xamarin.Forms as both these frameworks use native widgets and implement UI once.

But as compared to Xamarin, React Native let the developer customize visual components and cut down the requirement of custom renders.

b. Designing Aspects

With Xamarin, the developer can design the UI in a platform-specific way or through Xamarin.Forms. For the greater flexibility, Custom Renderers can be deployed when the exact same look is desired across platforms. However, it takes time in the implementation while generating the Custom Renderers.

Verdict: Thanks to native tools and Xamarin.Forms, Xamarin takes the crown.

How To Choose Right Tool For Cross-Platform Mobile App Development?

The race of comparison between Xamarin and React Native ends here and by looking at the overall comparison, Xamarin does take a lead, but React Native is equally competitive. Both of these frameworks i.e. Xamarin Vs React Native are exceptionally well when we talk about the features and the functionality they have.

The choice of cross-platform mobile app development framework depends upon the app requirements, functionalities, and features. Every framework has its pros and cons, therefore, as per the need, the framework should be picked.

Xamarin vs React Native

We really hope that with the help of this article, we were able to clear up some of your doubts regarding the development of cross-platform mobile apps. To read more interesting articles on technologies related to app development companies, subscribe to MobileAppDaily.


결론.

const 컴파일 상수는 성능이 매우 중요하고 상수의 값이 절대로 바뀌지 않는 경우만 제한적으로 사용하는 것이 좋다.

 

readonly 런타임 상수는..

- const 에 비해 느리지만 유연성이 좋다.

- 어떤 타입과도 함께 사용할수 있다.

- 메서드내에서는 선언할 수 없다.

- 클래스별로 서로 다른 값을 가질 수 있다.

- 값을 변경 한 경우 리빌드 하지 않아도 런타임시 값을 참조하기 때문에 어샘블리만 리빌드 되어있으면 변경된 값을 가져올수 있다.

* 런타임에 값이 평가되어 값을 가지지 않고 상수에 대한 참조 컴파일 된다.

* 맴버 초기화 구문뿐 아니라 생성자를 통해서도 초기화 가능하다.

 

const 컴파일 타임 상수는..

- 속도가 빠르고 변경이 불가능하다.

- 내장자료형(primitive types)과 enums,string으로만 사용할 수 있다.

- const. 컴파일 타임 상수는 메서드내에서 정의될 수 있다.

- 하나의 값만 가질 수 있다.

- 값을 변경 한 경우 리빌드 해야함 참조한 프로젝트에서 변경된 값을 가져올수 있다.

 

1. 지역변수를 선언할 때는 var 를 사용하는 것이 낫다.

정확한 반환 타입을 알면 상관없지만 어설프게 정확한 반환타입을 알지 못한채 명시적 타입을 쓰게되면

득보다 실이 많다.

변수의 타입보다는 변수의 의미파악에 더 집중할 수 있게 한다.

가독성과 자동타입변환 과정으로 인해 버그를 만들수도 있지만

var 변수로 인해 가독성이 방해되는 코드라면 대부분

명시적으로 써도 가독성은 불편한건 마찬가지이다.

fatal signal 6 (sigabrt)

위 에러는 리소스 문제일 가능성이 큽니다.

전 Renderer 에서 폰트를 아래와 같이 정의했는데

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Editor> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.Typeface = Typeface.CreateFromAsset(base.Context.Assets, "Binggrae.ttf");
            }
        }

매번 Create 해서 발생된 문제였습니다.

아래 처럼 변경하니 에러가 해결되었습니다.

        private static Typeface typeface;

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Editor> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                if (typeface == null)
                {
                    typeface = Typeface.CreateFromAsset(base.Context.Assets, "Binggrae.ttf");
                }

                Control.Typeface = typeface;
            }
        }

c# 8 에서 부터 지원되는 문법으로 아래처럼 사용할 수 있다.

int[] arr = { 1, 2, 3, 4 };
var lastIndex = new Index(1, true);
int lastNum = arr[lastIndex]; // 4
lastNum = arr[^1]; // 위 코드와 동일
nt[] arr = { 1, 2, 3, 4 };
Range range = 1..^1;
var sub = arr[range]; // [2, 3]
sub = arr[1..^1]; // 위 코드와 동일
var sub2 = arr[1..]; // [2, 3, 4]
var sub3 = arr[..3]; // [1, 2, 3]
var sub4 = arr[..]; // [1, 2, 3, 4]
string s = "Hello, World!"[..^8]; // "Hello"

 

파이썬과 동일하게.. 이건머.. 하는 짓? 이지?;;;

 

// selectPath : SQLite DB 파일 백업 폴더 위치

Java.IO.File sd = new Java.IO.File(selectPath);

// 폴더가 존재하지 않으면 만든다.

if (!sd.Exists())
{
    sd.Mkdirs();
}

Java.IO.File data = Android.OS.Environment.DataDirectory;
// System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);


FileChannel source = null;
FileChannel destination = null;

//  data 가 두번 붙는거 방지 (안드로이드 버전에 따라 다르게 나오는 부분 처리)

List<string> pathList = Constant.DBPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();

if (pathList[0] == "data")
{
    pathList.RemoveAt(0);
}

string path = string.Join("/", pathList);

string currentDBPath = path;

string backupDBPath = "test.db";
Java.IO.File currentDB = new Java.IO.File(data, currentDBPath);
Java.IO.File backupDB = new Java.IO.File(sd, backupDBPath);
try
{
    source = new FileInputStream(currentDB).Channel;
    destination = new FileOutputStream(backupDB).Channel;
    destination.TransferFrom(source, 0, source.Size());
    source.Close();
    destination.Close();
    Toast.MakeText(this, "백업 완료! - " + backupDB.Path, ToastLength.Long).Show();
}
catch (Java.Lang.Exception ex)
{
    ex.PrintStackTrace();
}

 

Xamarin.Forms 콤보박스 컨트롤인 Picker 컨트롤에는 화살표시가 없습니다.

 

화살표시를 나타내기 위해서는 렌더러를 이용해야합니다.

우선 화살표 이미지를 먼저 구해야합니다. (전 아래 이미지로..)

  (downarrow)

사용할 이미지를 Android 프로젝트의 Resources/drawable 폴더에, iOS 프로젝트의 Resources 폴더에 추가합니다.

 

먼저 .Net Standard 프로젝트에

CustomPicker.cs 를 추가합니다.

using Xamarin.Forms;

namespace Test.Cntrol
{
    public class CustomPicker : Picker
    {
        public static readonly BindableProperty ImageProperty =
            BindableProperty.Create(nameof(Image), typeof(string), typeof(CustomPicker), string.Empty);

        public string Image
        {
            get { return (string)GetValue(ImageProperty); }
            set { SetValue(ImageProperty, value); }
        }

        public CustomPicker() : base()
        {
            Margin = 3;
        }
    }
}

 

Android 프로젝트에 CustomPickerRenderer.cs 를 추가합니다.

using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Support.V4.Content;
using Test.Cntrol;
using Test.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace Test.Droid
{
    public class CustomPickerRenderer : PickerRenderer
    {
        CustomPicker element;

        public CustomPickerRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);

            element = (CustomPicker)this.Element;

            if (Control != null && this.Element != null && !string.IsNullOrEmpty(element.Image))
                Control.Background = AddPickerStyles(element.Image);
        }

        public LayerDrawable AddPickerStyles(string imagePath)
        {
            ShapeDrawable border = new ShapeDrawable();
            border.Paint.Color = Android.Graphics.Color.Gray;
            border.SetPadding(10, 10, 10, 10);
            border.Paint.SetStyle(Paint.Style.Stroke);

            Drawable[] layers = { border, GetDrawable(imagePath) };
            LayerDrawable layerDrawable = new LayerDrawable(layers);
            layerDrawable.SetLayerInset(0, 0, 0, 0, 0);

            return layerDrawable;
        }

        private BitmapDrawable GetDrawable(string imagePath)
        {
            int resID = Resources.GetIdentifier(imagePath, "drawable", this.Context.PackageName);
            var drawable = ContextCompat.GetDrawable(this.Context, resID);
            var bitmap = ((BitmapDrawable)drawable).Bitmap;

            var result = new BitmapDrawable(Resources, Bitmap.CreateScaledBitmap(bitmap, 70, 70, true));
            result.Gravity = Android.Views.GravityFlags.Right;

            return result;
        }
    }
}

 

iOS 프로젝트에도 CustomPickerRenderer.cs 를 추가합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Foundation;
using Test.Cntrol;
using Test.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))]
namespace Test.iOS
{
    public class CustomPickerRenderer : PickerRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);

            var element = (CustomPicker)this.Element;

            if (this.Control != null && this.Element != null && !string.IsNullOrEmpty(element.Image))
            {
                var downarrow = UIImage.FromBundle(element.Image);
                Control.RightViewMode = UITextFieldViewMode.Always;
                Control.RightView = new UIImageView(downarrow);
            }
        }
    }
}

 

이제 화면 상에서 아래 처럼 컨트롤을 정의한후 데이터를 바인딩하면

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:cntrol="clr-namespace:Test.Cntrol"
             x:Class="Test.MainPage">
    <StackLayout Spacing="5">
      
      <cntrol:CustomPicker x:Name="customPicker"
                           HeightRequest="40"
                           Margin="10"
                           Image="downarrow"
                           Title="Custom Picker"/>
    </StackLayout>
</ContentPage>

아래처럼 화살표시가 Picker 에 표시됩니다.

 

 

 

계속 폰으로 디버깅 하다가 원격으로 붙을 일이있어 에뮬레이터를 가동시켰는데

아래와 같이 떴다.. ??? 머지???

이전에 잘 사용했던 놈인데 갑자기 비번을 물어본다...;;

 

해결방법은 에뮬레이터 장치를 초기화해야한다. (원인은.. 모름모름..)

도구->Android->Android Device Manager 에서 장치목록에서 마우스 우클릭 후 나온 메뉴에서 '초기화' 를 하면된다.

 

아래처럼 에뮬레이터가 잘 실행되었다.

 

TabbedPage 는 각 화면에서 좌우 스크롤을 하면 옆 페이지로 이동합니다.

그런데 이를 막고 싶을때가 있습니다.

만약 좌우 스크롤이 탭안의 페이지에서 사용될때가 그 경우가 되겠죠

이를 막는 방법은 TabbedPage 의 소스상에서 아래의 코드를 넣어주면 됩니다.

 

this.On<Xamarin.Forms.PlatformConfiguration.Android>().SetIsSwipePagingEnabled(false); 

아래처럼 좌우 스크롤을 해도 탭페이지가 이동되지 않습니다.

 

 

 

 

ListView 에서 선택한 셀에 대한 색상을 변경하는 방법입니다.

아래는 기본 적인 ListView 코드입니다.

        <ListView x:Name="originalListView"
                  RowHeight="30"
                  SeparatorVisibility ="Default"
                  SeparatorColor="Black"
                  Margin="10"                  >
            <ListView.Header>
                <StackLayout Orientation="Horizontal"
                             VerticalOptions="CenterAndExpand"
                             Padding="0"
                             Spacing="0"
                             BackgroundColor="Gray"
                             HeightRequest="30">
                    <Label  Text="항목"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            FontSize="12"
                            WidthRequest="80"/>
                    <Label  Text="데이터1"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                    <Label  Text="데이터2"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout>
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Orientation="Horizontal"
                                             Padding="0"
                                             Spacing="0">
                                    <Label  Text="{Binding Content}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data1}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data2}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

위처럼 Page 에 위치 시킨 후 구동하면 아래와 같이 선택한 컬럼에 대해서 아래와 같이 나타납니다.

(선택 색상이 전혀 어울리지 않습니다.^^; - 안드로이드 버젼별로 색이 다름)

 

이상한 자주색이 맘에 들지 않습니다.; 선택한 컬럼에 대해 색상을 변경해봅시다.

먼저 .Net Standard 프로젝트에 ExtendedViewCell 클래스를 추가합니다.

using Xamarin.Forms;

namespace Test.Extended
{
    public class ExtendedViewCell : ViewCell
    {
        public static readonly BindableProperty SelectedBackgroundColorProperty =
            BindableProperty.Create("SelectedBackgroundColor",
                                    typeof(Color),
                                    typeof(ExtendedViewCell),
                                    Color.Default);

        public Color SelectedBackgroundColor
        {
            get { return (Color)GetValue(SelectedBackgroundColorProperty); }
            set { SetValue(SelectedBackgroundColorProperty, value); }
        }
    }
}

여기선 단순히 SelectedBackgroundColor 속성을 선언만 할 뿐입니다.

실질적인 동작은 각 장치별 렌더러에서 맡아서 처리하게됩니다.

 

Android 프로젝트로 가서 ExtendedViewCellRenderer 클래스를 추가합니다.

using Android.Content;
using Android.Graphics.Drawables;
using Android.Views;
using Test.Droid.ExtendedRenderer;
using Test.Extended;
using System.ComponentModel;
 
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace Test.Droid.ExtendedRenderer
{
    public class ExtendedViewCellRenderer : ViewCellRenderer
    {
        private Android.Views.View cellCoreView;
        private Drawable unSelectedBackground;
        private bool isSelected;

        protected override Android.Views.View GetCellCore(
            Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
        {
            this.cellCoreView = base.GetCellCore(item, convertView, parent, context);

            this.isSelected = false;
            this.unSelectedBackground = cellCoreView.Background;

            return cellCoreView;
        }

        protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args)
        {
            base.OnCellPropertyChanged(sender, args);

            if (args.PropertyName == "IsSelected")
            {
                this.isSelected = !this.isSelected;

                if (this.isSelected)
                {
                    var extendedViewCell = sender as ExtendedViewCell;
                    this.cellCoreView.SetBackgroundColor(extendedViewCell.SelectedBackgroundColor.ToAndroid());
                }
                else
                {
                    this.cellCoreView.SetBackground(this.unSelectedBackground);
                }
            }
        }
    }
}

 

iOS 프로젝트로 가서 ExtendedViewCellRenderer 클래스를 추가합니다.

using Test.Extended;
using Test.iOS.ExtendedRenderer;
using UIKit;

using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace Test.iOS.ExtendedRenderer
{
    public class ExtendedViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            var cell = base.GetCell(item, reusableCell, tv);
            var view = item as ExtendedViewCell;
            cell.SelectedBackgroundView = new UIView
            {
                BackgroundColor = view.SelectedBackgroundColor.ToUIColor(),
            };

            return cell;
        }
    }
}

사전 작업은 완료되었습니다.

 

이제 기본 코드에서 ExtendedViewCell 을 사용하도록 변경합니다. (굵게표시된부분)

        <ListView x:Name="extendedListView"
                  RowHeight="30"
                  SeparatorVisibility ="Default"
                  SeparatorColor="Black"
                  Margin="10"                  >
            <ListView.Header>
                <StackLayout Orientation="Horizontal"
                             VerticalOptions="CenterAndExpand"
                             Padding="0"
                             Spacing="0"
                             BackgroundColor="Gray"
                             HeightRequest="30">
                    <Label  Text="항목"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            FontSize="12"
                            WidthRequest="80"/>
                    <Label  Text="데이터1"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                    <Label  Text="데이터2"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <extended:ExtendedViewCell SelectedBackgroundColor="LightGray">
                        <ViewCell.View>
                            <StackLayout>
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Orientation="Horizontal"
                                             Padding="0"
                                             Spacing="0">
                                    <Label  Text="{Binding Content}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data1}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data2}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </extended:ExtendedViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Selected Color 로 LightGray 를 설정한 결과는 아래과 같습니다.

완료!

+ Recent posts