【发布时间】:2016-05-09 17:55:03
【问题描述】:
想要使我的 Xamarin Forms 应用程序具有一致的外观,我需要知道如何更改选项卡式页面选项卡栏图标的字体。按照 iOS API 的建议使用 UITabBarItem.Appearance 似乎没有任何效果。这样做有什么必要?
【问题讨论】:
标签: xamarin xamarin.ios xamarin.forms
想要使我的 Xamarin Forms 应用程序具有一致的外观,我需要知道如何更改选项卡式页面选项卡栏图标的字体。按照 iOS API 的建议使用 UITabBarItem.Appearance 似乎没有任何效果。这样做有什么必要?
【问题讨论】:
标签: xamarin xamarin.ios xamarin.forms
你需要编写一个像这样的自定义渲染器,从下面的代码中获取线索!它有你想要的
[assembly: ExportRenderer(typeof(ExtendedTabbedPage), typeof(TabbedPageCustom))]
namespace App.iOS
{
public class TabbedPageCustom : TabbedRenderer
{
public TabbedPageCustom ()
{
TabBar.TintColor = UIKit.UIColor.White;
TabBar.BarTintColor = UIKit.UIColor.White;
TabBar.BackgroundColor = UIKit.UIColor.Red;
}
protected override void OnElementChanged (VisualElementChangedEventArgs e)
{
base.OnElementChanged (e);
// Set Text Font for unselected tab states
UITextAttributes normalTextAttributes = new UITextAttributes();
normalTextAttributes.Font = UIFont.FromName("ChalkboardSE-Light", 20.0F); // unselected
normalTextAttributes.TextColor = UIKit.UIColor.Blue;
UITabBarItem.Appearance.SetTitleTextAttributes(normalTextAttributes, UIControlState.Normal);
}
public override UIViewController SelectedViewController {
get {
UITextAttributes selectedTextAttributes = new UITextAttributes();
selectedTextAttributes.Font = UIFont.FromName("ChalkboardSE-Bold", 20.0F); // SELECTED
if (base.SelectedViewController != null)
{
base.SelectedViewController.TabBarItem.SetTitleTextAttributes(selectedTextAttributes, UIControlState.Normal);
}
return base.SelectedViewController;
}
set {
base.SelectedViewController = value;
foreach (UIViewController viewController in base.ViewControllers)
{
UITextAttributes normalTextAttributes = new UITextAttributes();
normalTextAttributes.Font = UIFont.FromName("ChalkboardSE-Light", 20.0F); // unselected
normalTextAttributes.TextColor = UIKit.UIColor.Blue;
viewController.TabBarItem.SetTitleTextAttributes(normalTextAttributes, UIControlState.Normal);
}
}
}
}
}
【讨论】:
UITabBarItem.Appearance.SetTitleTextAttributes 都无法完成这项工作。 Xamarin Forms 不尊重该设置。
这是一个特别有趣的问题。我试过了:
使用UITabBarItem.Appearance.SetTitleTextAttributes 方法将UITextAttribute 更新为UIControlState.Normal 的我的字体(大小9.0f)。这似乎没有任何区别。
我发现设置UINavigationBar.Appearance.SetTitleTextAttributes 会同时更新UINavigationBar 文本外观和UITabBarItem 文本外观。
这是一个问题,因为标签页项目的字体太大了。
TabbedRenderer
受我在某处看到的示例的启发,我在 iOS 项目中将 TabbedRenderer 子类化。
我尝试覆盖TabbedRenderer.SelectedViewController 属性的设置器并循环通过ViewControllers 属性来设置它们的项目。图标将以标准字体显示,但一旦用户更改选项卡,它们都会更新为所需的字体。快到了!
然后我尝试覆盖 AddChildViewController 并在添加控制器后更新该控制器的 TabBarItem,但最终没有效果。添加页面的TabBarItem 在添加控制器后的某个时间点进行更新。
最终我发现覆盖 ViewWillAppear 并设置当时所有标签栏项目的外观似乎可以完成我想要的工作。
我在this gist 中包含了一个示例。
【讨论】: