使用自定义渲染器的Xamarin窗体编辑器上的占位符边距



我在Xamarin Forms项目的一个页面上有一个编辑器,我想通过添加一点边距来修改占位符文本位置。

我能够在用户键入的文本中添加页边空白(但不是占位符(;TextContainerInset"在我的iOS自定义渲染器中。


protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{

base.OnElementChanged(e);
this.Control.InputAccessoryView = null;
this.Control.Layer.CornerRadius = 10;
this.Control.Layer.BorderColor = UIColor.LightGray.CGColor;
this.Control.Layer.BorderWidth = (nfloat)0.5;
this.Control.TextContainerInset = new UIEdgeInsets(15,15,15,15);    

}

但是,此插入不适用于占位符位置。

有没有一种方法可以使用自定义渲染器移动占位符位置?

您可以设置如下填充:

public class MyEntryRenderer : EntryRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged (e);

if (Control != null) {
Control.LeftView = new UIView(new CGRect(0,0,15,0));
Control.LeftViewMode = UITextFieldViewMode.Always;
Control.RightView = new UIView(new CGRect(0, 0, 15, 0));
Control.RightViewMode = UITextFieldViewMode.Always;
}
}
}

编辑器的工作:

扭曲框架中的编辑器并设置填充,如:

<StackLayout Margin="20">
<Frame CornerRadius="10" BorderColor="Gray" HeightRequest="50" Padding="5,10,5,10" HasShadow="False">
<Editor Placeholder="Enter the editor text" ></Editor>
</Frame>
</StackLayout>

底层的UITextView不实现占位符。但是,如果您查看从UITextView派生的EditorRenderer代码,Xamarin已经在那里实现了占位符。

private UILabel _placeholderLabel;

通过使用反射,我可以获得一个指向UILabel_placeholderLabel的指针,但我一生都无法移动它。

如果有人能帮我移动UILabel,我相信我们已经找到了答案!

protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if (Control != null)
{
editor = e.NewElement as EditorEx;
//Use reflection to access private placeholder in parent
//https://www.c-sharpcorner.com/UploadFile/6f0898/how-to-access-a-private-member-of-a-class-from-other-class/
System.Reflection.FieldInfo receivedObject = typeof(EditorRenderer).GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[1];
_placeholderLabel = receivedObject.GetValue(this) as UILabel;
_placeholderLabel.Text = "move me!!; //this works
_placeholderLabel.BackgroundColor = UIColor.Green; //this works
//put it on another message to see if that solves it (it doesn't)
Device.BeginInvokeOnMainThread(() =>
{
//HELP NEEDED HERE!!!
//_placeholderLabel.Frame = new CGRect(-15, -10, 500, 30); //doesn't work
//_placeholderLabel.Bounds = new CGRect(-15, -10, 500, 30); //doesn't work
_placeholderLabel.LayoutMargins = new UIEdgeInsets(-15, -10, 5, 5); //doesn't work
});
}
}

最新更新