かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Xamarin.FormsでLabelに下線を引きたい

デフォルトで引けないんですね。知らなかった。

Effectを使おう

ということでカスタムレンダラー案件かなと思ったらEffectでいけるっぽいです。

Android

Androidに以下のようなクラスを追加します。

using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ResolutionGroupName("Sample")]
[assembly: ExportEffect(typeof(PrismUnityApp13.Droid.UnderlineEffect), "UnderlineEffect")]
namespace PrismUnityApp13.Droid
{
    public class UnderlineEffect : PlatformEffect
    {


        protected override void OnAttached()
        {
            var textView = this.Control as TextView;
            if (textView == null) { return; }

            textView.PaintFlags = textView.PaintFlags | Android.Graphics.PaintFlags.UnderlineText;
        }

        protected override void OnDetached()
        {
        }
    }
}

iOS

iOSは動作確認取れる環境はないのですが、UILabelに対して以下のようにすると下線が引けるっぽい?

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

[assembly: ResolutionGroupName("Sample")]
[assembly: ExportEffect(typeof(PrismUnityApp13.iOS.UnderlineEffect), "UnderlineEffect")]
namespace PrismUnityApp13.iOS
{
    public class UnderlineEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var label = this.Control as UILabel;
            if (label == null) { return; }

            var text = label.Text;
            label.AttributedText = new NSAttributedString(
                text,
                underlineStyle: NSUnderlineStyle.Single);
        }

        protected override void OnDetached()
        {
        }
    }
}

PCL

そして、PCLでEffectを作ります。

using Xamarin.Forms;

namespace PrismUnityApp13
{
    public class UnderlineEffect : RoutingEffect
    {
        public UnderlineEffect() : base("Sample.UnderlineEffect")
        {
        }
    }
}

XAML

そして、XAMLでLabelにEffectを追加します。

<Label Text="{Binding Title}">
  <Label.Effects>
    <local:UnderlineEffect />
  </Label.Effects>
</Label>

実行

Androidしか実行環境持ってないのでiOS試せてないのですが、Androidでは以下のように下線が引かれました。

f:id:okazuki:20161205233948p:plain

まとめ

Effect初めて触ってみたけど簡単お手軽な感じですね。いいかも。