Skip to content

Instantly share code, notes, and snippets.

@Driv4r
Last active June 14, 2016 23:32
Show Gist options
  • Save Driv4r/09995a6167551bd73bb2b24377b4fb7a to your computer and use it in GitHub Desktop.
Save Driv4r/09995a6167551bd73bb2b24377b4fb7a to your computer and use it in GitHub Desktop.
Custom Renderers - Xamarin (https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/) CustomView.cs goes in the PCL project Views folder. MainPage.cs/MainPage.xaml goes in the PCL project Pages folder. CustomViewRenderer.cs goes in the iOS/Android project
using Xamarin.Forms;
namespace Myproject.Views
{
public class CustomView : View
{
public CustomView()
{
}
}
}
using Myproject.iOS.Renderers;
using Myproject.Views;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomView), typeof(CustomViewRenderer))]
namespace Myproject.iOS.Renderers
{
public class CustomViewRenderer : ViewRenderer<CustomView, UIControl>
{
/// <summary>
/// Method used to instantiate the native view.
/// </summary>
protected override void OnElementChanged(ElementChangedEventArgs<CustomView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
UIButton btn = new UIButton();
//Customize the button here.
SetNativeControl(btn);
}
}
}
}
//Use of the view in the xamarin forms project using code.
public class MainPage : ContentPage
{
public MainPage ()
{
Content = new StackLayout {
Children = {
new Label {
Text = "This is my custom renderer",
},
new CustomView {
VerticalOptions="StartAndExpand",
}
},
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
}
}
<ContentPage ...
xmlns:local="clr-namespace:Myproject.Views;assembly=Myproject"
...>
...
<Label Text="This is my custom renderer." />
<local:CustomView VerticalOptions="StartAndExpand" /> <!-- Use anything that a Xamarin Forms View can normall use -->
...
</ContentPage>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment