首页 > 解决方案 > 如何为 Xamarin 标签添加双下划线?

问题描述

我有一些文字和一些文字,我想添加双下划线的效果。

<Label Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit."/>

我尝试在带有标签的 FlexLayout 中使用 BoxView,但正因为如此,出现了自动换行问题。

<FlexLayout JustifyContent="Start" AlignContent="Start" AlignItems="Start" FlowDirection="LeftToRight" Wrap="Wrap" >
    <Label Text="Lorem " FontAttributes="Italic"/>
    <StackLayout Spacing="0">
        <Label Text="ipsum" FontAttributes="Italic"/>
        <BoxView WidthRequest="2" BackgroundColor="#747474" Color="#747474" HeightRequest="0.5"/>
        <BoxView WidthRequest="2" BackgroundColor="#747474" Color="#747474" Margin="0,2,0,0" HeightRequest="0.5"/>
    </StackLayout>
    <Label Text=" dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit." FontAttributes="Italic"/>
</FlexLayout>

在此处输入图像描述

标签: xamarinxamarin.formsxamarin.androidxamarin.ios

解决方案


您可以使用自定义渲染器并在特定平台上实现它。

此外,iOS 中默认提供双下划线。但在 Android 中,它不可用。

在 iOS 中

using Foundation;
using UIKit;

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

using App34.iOS;

[assembly:ExportRenderer(typeof(Label),typeof(MyLabelRenderer))]

namespace App34.iOS
{
    public class MyLabelRenderer:LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if(Control!=null)
            {
                var content = Control.Text;

                UIStringAttributes attributes = new UIStringAttributes() { UnderlineStyle = NSUnderlineStyle.Double,UnderlineColor=UIColor.Red };

                NSMutableAttributedString str = new NSMutableAttributedString(content, attributes);

                Control.AttributedText = str;
            }

        }
    }
}

在安卓中

样式为单下划线。


using Android.Content;

using Android.Widget;

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

using App34.Droid;
using Android.Text;


[assembly: ExportRenderer(typeof(Label), typeof(MyLabelRenderer))]
namespace App34.Droid
{
    public class MyLabelRenderer : LabelRenderer
    {
        public MyLabelRenderer(Context context) : base(context)
        {

        }

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

            if(Control!=null)
            {

               Control.SetText(Html.FromHtml("<u>" + Control.Text +"</u>",FromHtmlOptions.ModeLegacy),TextView.BufferType.Normal);
            }

        }

    }

}

推荐阅读