Skip to content

Instantly share code, notes, and snippets.

@programmation
Created September 1, 2015 13:18
Show Gist options
  • Save programmation/5e356ff31256603f5625 to your computer and use it in GitHub Desktop.
Save programmation/5e356ff31256603f5625 to your computer and use it in GitHub Desktop.
Vertical centring UILabel subclass implementing Xamarin.Forms LabelRenderer
using System;
using System.ComponentModel;
using CoreGraphics;
using CustomRendererTest.Controls;
using CustomRendererTest.iOS.Renderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer (typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace CustomRendererTest.iOS.Renderers
{
public class CustomUILabel
: UILabel
{
public Xamarin.Forms.TextAlignment YAlign { get; set; }
public override void DrawText (CGRect rect)
{
var size = SizeThatFits (Bounds.Size);
var insets = UIEdgeInsets.Zero;
if (YAlign == Xamarin.Forms.TextAlignment.Start) {
BaselineAdjustment = UIBaselineAdjustment.AlignBaselines;
}
if (YAlign == Xamarin.Forms.TextAlignment.Center) {
BaselineAdjustment = UIBaselineAdjustment.AlignCenters;
insets.Top = (Bounds.Height - size.Height) / 2;
insets.Bottom = insets.Top;
}
if (YAlign == Xamarin.Forms.TextAlignment.End) {
BaselineAdjustment = UIBaselineAdjustment.AlignBaselines;
insets.Top = Bounds.Height - size.Height;
}
var labelRect = new CGRect (rect.X, rect.Y + insets.Top, rect.Width, rect.Y + size.Height);
base.DrawText (labelRect);
}
}
public class CustomLabelRenderer
: ViewRenderer<CustomLabel, CustomUILabel>
{
public CustomLabelRenderer ()
{
}
protected override void OnElementChanged (ElementChangedEventArgs<CustomLabel> e)
{
base.OnElementChanged (e);
if (e.NewElement == null) {
return;
}
if (Control == null) {
var label = new CustomUILabel ();
label.BackgroundColor = Element.BackgroundColor.ToUIColor ();
label.Text = Element.Text;
label.TextColor = Element.TextColor.ToUIColor ();
label.YAlign = Element.YAlign;
SetNativeControl (label);
}
}
protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
if (Control == null) {
return;
}
if (e.PropertyName == View.BackgroundColorProperty.PropertyName) {
Control.BackgroundColor = Element.BackgroundColor.ToUIColor ();
}
if (e.PropertyName == Label.TextProperty.PropertyName) {
Control.Text = Element.Text;
}
if (e.PropertyName == Label.TextColorProperty.PropertyName) {
Control.TextColor = Element.TextColor.ToUIColor ();
}
if (e.PropertyName == Label.YAlignProperty.PropertyName) {
Control.YAlign = Element.YAlign;
}
Control.SetNeedsDisplay ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment