Reputation: 53
I have created a custom navigation page in xamarin in order to change the font of the toolbar items in the navigation bar.
All went well, however the font is not changing on all toolbar items, just the last one for some reason.
As you can see, I have also tried to change the color to red, apart from the font however this is only working on the last item aswell.
XAML:
<ContentPage.ToolbarItems>
<ToolbarItem x:Name="MenuItem1"
Order="Primary"
Text="x1"
Priority="0" />
<ToolbarItem x:Name="MenuItem2"
Order="Primary"
Text="x2"
Priority="1" />
<ToolbarItem x:Name="MenuItem3"
Order="Primary"
Text="x3"
Priority="2" />
<ToolbarItem x:Name="MenuItem4"
Order="Primary"
Text="x4"
Priority="3" />
</ContentPage.ToolbarItems>
iOS:
public class FontAwesomeNavigationPageRenderer : NavigationRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if(e.NewElement != null)
{
var att = new UITextAttributes
{
Font = UIFont.FromName("FontAwesome5Pro-Light", 18),
TextColor = UIColor.Red
};
UIBarButtonItem.Appearance.SetTitleTextAttributes(att, UIControlState.Normal);
}
}
}
What am I missing?
Upvotes: 0
Views: 562
Reputation: 53
I finally managed to get this working thanks to some help from @iSpain17 in the comment above.
Below is my code for the iOS part
public override void ViewDidAppear(bool animated) {
base.ViewDidAppear(animated);
SetNavigationButtonsPage();
}
private void SetNavigationButtonsPage()
{
var att = new UITextAttributes
{
Font = UIFont.FromName("FontAwesome5Pro-Light", 16),
};
var navigationItems = (this as UINavigationController).NavigationBar.Items;
List<UIBarButtonItem> barButtonItems = new List<UIBarButtonItem>();
foreach (UINavigationItem item in navigationItems)
{
barButtonItems.AddRange(item.LeftBarButtonItems);
barButtonItems.AddRange(item.RightBarButtonItems);
}
foreach (UIBarButtonItem bbItem in barButtonItems)
{
//change appearance for each bbItem
bbItem.SetTitleTextAttributes(att, UIControlState.Normal);
}
}
The solution was to change the method being used from OnElementChanged to ViewDidAppear!
Thank You :)
Upvotes: 0
Reputation: 3053
NavigationRenderer is a UINavigationController in iOS, so you can do the following:
var navController = this as UINavigationController;
var navigationItems = navController.NavigationBar.Items)
List<UIBarButtonItem> barButtonItems = new List<UIBarButtonItem>();
foreach(UINavigationItem item in navigationItems) {
barButtonItems.AddRange(item.NavigationBar.leftBarButtonItems);
barButtonItems.AddRange(item.NavigationBar.rightBarButtonItems);
}
foreach(UIBarButtonItem bbItem in barButtonItems) {
//change appearance for each bbItem
}
This will list every UINavigationItem
for this UINavigationController
, and then take every UIBarButtonItem
associated with them.
Upvotes: 1