Xamarin Forms将占位符添加到iOS的编辑器中

Bjt*_*776 2 xamarin.ios xamarin.forms

如何在Xamarin Forms for iOS中为编辑器添加占位符?

我尝试通过自定义渲染器添加为Control.Layer,但找不到与之相关的属性.

请帮忙.

Jay*_*tel 7

请尝试以下代码:

PCL:

using System;
using Xamarin.Forms;

namespace ABC.CustomViews
{
    public class PlaceholderEditor : Editor
    {
        public static readonly BindableProperty PlaceholderProperty =
            BindableProperty.Create<PlaceholderEditor, string>(view => view.Placeholder, String.Empty);

        public PlaceholderEditor()
        {
        }

        public string Placeholder
        {
            get
            {
                return (string)GetValue(PlaceholderProperty);
            }

            set
            {
                SetValue(PlaceholderProperty, value);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

iOS(CustomeRenderer):

using UIKit;
using ABC.CustomViews;
using ABC.iOS.CustomRenderer;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(PlaceholderEditor), typeof(PlaceholderEditorRenderer))]
namespace ABC.iOS.CustomRenderer
{
    public class PlaceholderEditorRenderer : EditorRenderer
    {
        private string Placeholder { get; set; }

        protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
        {
            base.OnElementChanged(e);
            var element = this.Element as PlaceholderEditor;

            if (Control != null && element != null)
            {
                Placeholder = element.Placeholder;
                Control.TextColor = UIColor.LightGray;
                Control.Text = Placeholder;

                Control.ShouldBeginEditing += (UITextView textView) =>
                {
                    if (textView.Text == Placeholder)
                    {
                        textView.Text = "";
                        textView.TextColor = UIColor.Black; // Text Color
                    }

                    return true;
                };

                Control.ShouldEndEditing += (UITextView textView) =>
                {
                    if (textView.Text == "")
                    {
                        textView.Text = Placeholder;
                        textView.TextColor = UIColor.LightGray; // Placeholder Color
                    }

                    return true;
                };
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

  _replyEditor = new PlaceholderEditor
  {
        Placeholder = "Placeholder Text"
  };
Run Code Online (Sandbox Code Playgroud)