如何在Xamarin表单中设置Entry的顶部填充

时间:2016-06-21 12:13:35

标签: c# xamarin xamarin.ios xamarin.forms

在我的Xamarin表单应用程序中,我需要为iOS中的Entry控件设置一个顶部填充。我为Entry创建了渲染器,但只有我能够设置左右填充。请帮我。以下是我的入门渲染器

public class CustomRenderer: 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;

        }
    }

}

2 个答案:

答案 0 :(得分:5)

要做到这一点,我们需要做两件事:

  1. 增加Xamarin.Forms
  2. Entry的高度
  3. 创建iOS自定义渲染器,将文本与UITextField的底部对齐 enter image description here
  4. 增加Xamarin.Forms中的条目高度

    在此示例中,我使用RelativeLayout将填充条目的高度设置为50 Constraint.Constant(50)

    using System;
    
    using Xamarin.Forms;
    
    namespace CustomEntrySample
    {
        public class EntryWithTopPadding : Entry
        {
        }
    
        public class App : Application
        {
            public App()
            {
                var normalEntry = new Entry
                {
                    Text = "This Entry Has Normal Padding",
                    BackgroundColor = Color.Lime
                };
    
                var paddedEntry = new EntryWithTopPadding
                {
                    Text = "This Entry Has Extra Top Padding",
                    BackgroundColor = Color.Aqua
                };
    
                var mainLayout = new RelativeLayout();
                mainLayout.Children.Add(
                    normalEntry,
                    Constraint.Constant(0),
                    Constraint.RelativeToParent(parent => parent.Y + 10),
                    Constraint.RelativeToParent(parent => parent.Width)
                );
                mainLayout.Children.Add(
                    paddedEntry,
                    Constraint.Constant(0),
                    Constraint.RelativeToView(normalEntry, (parent, view) => view.Y + view.Height + 10),
                    Constraint.RelativeToParent(parent => parent.Width),
                    Constraint.Constant(50)
                );
    
                MainPage = new NavigationPage(
                    new ContentPage
                    {
                        Title = "Title",
                        Content = mainLayout,
                        Padding = new Thickness(10, 0, 10, 0)
                    }
                );
            }
        }
    }
    

    创建自定义渲染器以将文本对齐到UITextField的底部

    VerticalAlignment的{​​{1}}属性设置为UITextField

    UIControlContentVerticalAlignment.Bottom

答案 1 :(得分:0)

使用此方法为输入单元格设置填充:

IOS中的填充:

Control.LeftView = new UIView(new CGRect(0,15,0,0));
Control.LeftViewMode = UITextFieldViewMode.Always;
Control.RightView = new UIView(new CGRect(0,10, 0, 0));
Control.RightViewMode = UITextFieldViewMode.Always;

在Android中填充:

Control.SetPadding(0, 10, 0, 0);

因此,您可以设置该值以使文本从特定位置开始。