代码之家  ›  专栏  ›  技术社区  ›  DarkW1nter

Xamarin表单-自定义呈现到IOS中的中心页标题

  •  0
  • DarkW1nter  · 技术社区  · 6 年前

    在xamarin表单中,我试图左对齐页面标题,我知道我需要一个自定义的呈现器,但我不知道在下面的代码后面该怎么做。

    这甚至可能不正确,但我认为我需要创建一个页面呈现器并在那里进行对齐?

    [assembly: ExportRenderer(typeof(Page), typeof(gl_mobile_app.iOS.TitleExRenderer))]
    namespace gl_mobile_app.iOS
    {
        public class TitleExRenderer : Xamarin.Forms.Platform.iOS.PageRenderer
        {
            protected override void OnElementChanged(VisualElementChangedEventArgs e)
            {
                base.OnElementChanged(e);
                // align title
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   GiampaoloGabba    6 年前

    这并没有得到苹果官方的支持。 default UINavigationBar 是的。

    你可以尝试一个技巧:在topitem.leftbarbuttonem中放置一个标签,不要使用默认的title属性

    在自定义渲染器中类似于以下内容:

    var label = new UILabel();
    //this is the variable containing the title you need to pass it as a bindable property
    label.Text = title; 
    label.TextAlignment = UITextAlignment.Left;
    label.SizeToFit();
    NavigationController.NavigationBar.TopItem.LeftBarButtonItem = new UIBarButtonItem(label);
    

    更新

    你也可以阅读这篇优秀的博客文章: http://www.xamboy.com/2017/12/06/navigation-bar-customization-in-xamarin-forms/

    更新2

    您可以尝试获取默认页面标题,在左侧位置使用它,然后对其进行处理,如下所示:

    var label = new UILabel();
    //get the default title
    label.Text =  NavigationController.NavigationBar.TopItem.Title; 
    label.TextAlignment = UITextAlignment.Left;
    label.SizeToFit();
    
    //empty the default title (try with empty string or null if empty doesnt work)
    NavigationController.NavigationBar.TopItem.Title = "";    
    
    NavigationController.NavigationBar.TopItem.LeftBarButtonItem = new UIBarButtonItem(label);
    

    这是未经测试的,如果成功请告诉我:)