【问题标题】:Xamarin Forms - custom renderer to centre page title in iosXamarin Forms - 自定义渲染器以在 ios 中居中页面标题
【发布时间】:2018-06-27 17:43:01
【问题描述】:

在 Xamarin Forms 中,我试图左对齐页面标题,我知道我需要一个自定义渲染器,但我不确定在下面的代码之后该去哪里。

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

[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
        }
    }
}

【问题讨论】:

    标签: c# xamarin.forms custom-renderer


    【解决方案1】:

    这在default UINavigationBar 中不受苹果官方支持。

    您可以尝试一个技巧:在 TopItem.LeftBarButtonItem 中放置一个标签,并且不要使用默认的 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);
    

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

    【讨论】:

    • 嗨,谢谢你,如果我对标题进行硬编码,它就可以工作,但是有没有办法可以使用实际的页面标题,同时将页面标题设置为 null?我似乎无法访问渲染器中的标题(显然做错了)
    • 我用一个技巧更新了答案,以获取默认页面标题并在左侧位置使用它
    • 再次感谢,我试过了,但我的问题是我在 OnAppearing 中设置了标题(来自数据库数据),渲染器在 OnAppearing 之前运行,所以只需要在构造函数中设置标题就可以了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2016-09-03
    • 2018-07-23
    • 1970-01-01
    相关资源
    最近更新 更多