wondering if anyone can help, the text on the webView is too small, I have an HTML that I have NO control over.
How can I increase the size?
I have tried Xamarin forms: Webview content default size is too small
but did not work for me as the page does not load at all.
Is this a bug?
Am I missing something?
Any suggestions
<WebView VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand">
<WebView.Source>
<HtmlWebViewSource
Html="{Binding HtmlSource}" />
</WebView.Source>
</WebView>
using Foundation;
using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))]
namespace MyCompany
{
public class MyWebViewRenderer : ViewRenderer<WebView, WKWebView>
{
WKWebView wkWebView;
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control != null) return;
var config = new WKWebViewConfiguration();
wkWebView = new WKWebView(Frame, config) {NavigationDelegate = new MyNavigationDelegate()};
SetNativeControl(wkWebView);
}
}
}
public class MyNavigationDelegate : WKNavigationDelegate
{
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
string fontSize = "200%";
string stringHtml = string.Format("document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '{0}'", fontSize);
WKJavascriptEvaluationResult handler = (NSObject result, NSError err) =>
{
if (err != null)
{
System.Console.WriteLine(err);
}
if (result != null)
{
System.Console.WriteLine(result);
}
};
webView.EvaluateJavaScript(stringHtml, handler);
}
}
The viewport element on a page
<meta name="viewport" content="width=device-width, initial-scale=1.0">
can be set with a renderer (omitting initial-scale):
using Foundation;
using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using MyNamespace.iOS.Renderers;
[assembly: ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))]
namespace MyNamespace.iOS.Renderers
{
//'WebViewRenderer' is obsolete: 'WebViewRenderer is obsolete as of 4.4.0. Please use the WkWebViewRenderer instead'
//WkWebViewRenderer inherits from WKWebView
public class MyWebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
WebView webView = Element as WebView;
webView.VerticalOptions = LayoutOptions.FillAndExpand;
string jScript = #"var meta = document.createElement('meta'); " +
"meta.setAttribute('name', 'viewport');" +
"meta.setAttribute('content', 'width=device-width');" +
"document.getElementsByTagName('head')[0].appendChild(meta);";
//WKUserScriptInjectionTime should be AtDocumentEnd
var userScript = new WKUserScript((NSString)jScript, WKUserScriptInjectionTime.AtDocumentEnd, true);
WKWebView wkWebView = this;
WKWebViewConfiguration wkWebViewConfig = wkWebView.Configuration;
wkWebViewConfig.UserContentController.AddUserScript(userScript);
}
}
}
}
See also "Using the viewport meta tag to control layout on mobile browsers" for a closer description on screen size, pixel scale, device orientation and zoom.
Note:
The meta tag seems to be set as follows in Safari in an iPad/iPhone simulator:
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
Related
I have embedded site in my assembly:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
WebView.Navigating += WebView_Navigating;
var resourceName = Program.GetResourceName("index.html");
WebView.Source = new UrlWebViewSource()
{
Url = "file://" + resourceName,
};
}
public void WebView_Navigating(object sender, WebNavigatingEventArgs args)
{
if (args.Url.StartsWith("file://"))
{
return;
}
Device.OpenUri(new Uri(args.Url));
args.Cancel = true;
}
}
I have tried to figure out how to run it using WebView using Xamarin.Forms ...
I have got embedded resource from my assembly and I need somehow to load text based html into WebView ...
But I did not know how to do this ...
Is there some API for loading Embedded Resource into WebView ?
After some research I have found some solution:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlazorXamarinMobile.Web.Client;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace BlazorXamarinMobile
{
public partial class MainPage : ContentPage
{
Dictionary<string, string> _urlToHtml = new Dictionary<string, string>();
public MainPage()
{
InitializeComponent();
WebView.Navigating += WebView_Navigating;
(string embeddedResource, string text) = Program.GetResourceName("index.html");
embeddedResource = embeddedResource.Replace("wwwroot.index.html", "wwwroot/index.html");
var embeddedResourceUrl = "file://" + embeddedResource;
_urlToHtml.Add("file://BlazorXamarinMobile.Web.Client.wwwroot/".ToLower(), text);
_urlToHtml.Add(embeddedResourceUrl.ToLower(), text);
WebView.Source = new HtmlWebViewSource()
{
BaseUrl = "file://BlazorXamarinMobile.Web.Client.wwwroot/".ToLower(),
Html = text,
};
}
public void WebView_Navigating(object sender, WebNavigatingEventArgs args)
{
if (args.Url.StartsWith("file://"))
{
if (args.Url.Contains("wwwroot/"))
{
var html = _urlToHtml[args.Url];
WebView.Source = new HtmlWebViewSource()
{
Html = html,
};
}
return;
}
args.Cancel = true;
}
}
}
But WebView shows that Url is invalid !!
But if I load text directly it shows initial site and error to Reload application ... It happens due to that WebView tries to load from custom path files, but those files are inside of Assembly and it should be loaded manually with some kind of hook ...
Is it possible to do ?
If you want to load the enbeded site with webview, you could try the steps below.
Html: index.hyml
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Xamarin Forms</title>
</head>
<body>
<h1>Xamarin.Forms</h1>
<p>This is an Android web page.</p>
</body>
</html>
Xaml:
<ContentPage.Content>
<WebView x:Name="Webview_html" />
</ContentPage.Content>
Code Behind:XamarinDemo is my Xamarin.Forms project. I put the html embeded resource under the Form project.
string fileName = "XamarinDemo.index.html";
var assembly = typeof(XamarinDemo.MainPage).Assembly;
Stream stream = assembly.GetManifestResourceStream(fileName);
if (stream == null)
{
throw new InvalidOperationException(
String.Format("Cannot create stream from specified URL: {0}", fileName));
}
StreamReader reader = new StreamReader(stream);
string htmlString = reader.ReadToEnd();
HtmlWebViewSource html = new HtmlWebViewSource();
html.Html = htmlString;
Webview_html.Source = html;
Screenshot:
It seems like you are not referencing the location correctly, and possibly even placed your html file in an incorrect location. What tutorial are you following, did you follow the official documentation for Xamarin Forms Web Views?
You have to place the files in the right location- Assets in Android and Resources on iOS.
And then you have to get the BaseURL in the right way for each platform using DependencyService
And then, on Android you have to use a stream reader to read the file
I have an awkward problem with GestureRecognizers on Xamarin WebView:
Although the documentation any some questions/answers here and in Xamarin Forum say that WebView GestureRecognizers should all work, I can't get it to fire any event.
My XAML code looks like this:
<StackLayout BackgroundColor="LightGray" >
<WebView x:Name="webView" VerticalOptions="FillAndExpand" >
<WebView.GestureRecognizers>
<SwipeGestureRecognizer Direction="Left" Swiped="onSwiped"/>
</WebView.GestureRecognizers>
<WebView.Source>
<HtmlWebViewSource Html="{Binding HTML}" />
</WebView.Source>
</WebView>
</StackLayout>
Alternatives treid so far:
Same GestureRecognizer on the Title of the same page: works
Same GestureRecognizer on a ListView of another page: works
Tried Nuget package Vapolia.XamarinGestures which also didn't work on the webview
Tried to put the GestureRecoginzer on the StackLayout around the WebView: didn't work either.
Tried it on iOS device and simulator. Normally iOS should be the easy part here...
What I actually want to achieve: with a swipe left move forward to another (programatically defined) web page.
I assume those gestures are somehow absorbed by the webview for regular navigation, but I was wondering why some examples would say that all gestures work on the webview.
An alternative could be to add that target webpage to the webview history stack on the "forward" path.. but not sure how to do that.
Anyone has some hints?
You could use Custom Renderer to add the swipe event on specific platform. And handle them in Forms .
in Forms
create a CustomWebView
public class CustomWebView : WebView
{
public event EventHandler SwipeLeft;
public event EventHandler SwipeRight;
public void OnSwipeLeft() =>
SwipeLeft?.Invoke(this, null);
public void OnSwipeRight() =>
SwipeRight?.Invoke(this, null);
}
in Android
using Android.Content;
using Android.Views;
using App11;
using App11.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(MyWebViewRenderer))]
namespace App11.Droid
{
public class MyWebViewRenderer : WebViewRenderer
{
public MyWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
Control.SetOnTouchListener(new MyOnTouchListener((CustomWebView)Element));
}
}
public class MyOnTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
{
float oldX;
float newX;
CustomWebView myWebView;
public MyOnTouchListener(CustomWebView webView)
{
myWebView = webView;
}
public bool OnTouch(Android.Views.View v, MotionEvent e)
{
if (e.Action == MotionEventActions.Down)
{
oldX = e.GetX(0);
}
if (e.Action == MotionEventActions.Up)
{
newX = e.GetX();
if (newX - oldX > 0)
{
myWebView.OnSwipeRight();
}
else
{
myWebView.OnSwipeLeft();
}
}
return false;
}
}
}
in iOS
using App11;
using App11.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using ObjCRuntime;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(MyWebViewRenderer))]
namespace App11.iOS
{
public class MyWebViewRenderer:WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if(e.NewElement!=null)
{
this.BackgroundColor = UIColor.Red;
UISwipeGestureRecognizer leftgestureRecognizer = new UISwipeGestureRecognizer(this,new Selector("SwipeEvent:"));
leftgestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
UISwipeGestureRecognizer rightgestureRecognizer = new UISwipeGestureRecognizer(this, new Selector("SwipeEvent:"));
rightgestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Right;
leftgestureRecognizer.Delegate = new MyWebViewDelegate();
rightgestureRecognizer.Delegate = new MyWebViewDelegate();
this.AddGestureRecognizer(leftgestureRecognizer);
this.AddGestureRecognizer(rightgestureRecognizer);
}
}
[Export("SwipeEvent:")]
void SwipeEvent(UISwipeGestureRecognizer recognizer)
{
var webview = Element as CustomWebView;
if(recognizer.Direction == UISwipeGestureRecognizerDirection.Left)
{
webview.OnSwipeLeft();
}
else if(recognizer.Direction == UISwipeGestureRecognizerDirection.Right)
{
webview.OnSwipeRight();
}
}
}
public class MyWebViewDelegate: UIGestureRecognizerDelegate
{
public override bool ShouldRecognizeSimultaneously(UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer)
{
return false;
}
}
}
Now you just need to use it like
<local:CustomWebView x:Name="browser"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
SwipeLeft="browser_SwipeLeft"
SwipeRight="browser_SwipeRight">
There was an additional trick to make it finally work. All the above (correct) solution was ignored due to my Xamarin MasterDetailPage setup.
This was capturing all horizontal swipes and not putting them through to the HybridWebView.
MasterDetailPage.IsGestureEnabled = false;
finally fixed it and enabled the swipe gestures in my WebView.
Here's what my dialog box looks like with a dark theme.
Does anyone know of a way that the colors could be changed in a Xamarin Forms app so that the dialog displays with white text on a dark background?
Does anyone have an idea what the problem might be?
Option 1
You could change it in specific platforms by using DependencyService
in forms
create the interface
using Xamarin.Forms;
namespace xxx
{
public interface IPopUp
{
void Popup(string title, string message,Color titleColor,Color messageColor, EventHandler handler);
}
}
in iOS
using System;
using System.Text;
using xxx.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using xxx;
[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.iOS
{
public class PopupImplemention : IPopUp
{
public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
{
UIAlertController alertController = UIAlertController.Create(title,message,UIAlertControllerStyle.Alert);
var firstAttributes = new UIStringAttributes
{
ForegroundColor =titleColor.ToUIColor(),
};
var secondAttributes = new UIStringAttributes
{
ForegroundColor =messageColor.ToUIColor(),
};
alertController.SetValueForKey(new NSAttributedString(title, firstAttributes), new NSString("attributedTitle"));
alertController.SetValueForKey(new NSAttributedString(message, secondAttributes), new NSString("attributedMessage"));
UIAlertAction cancelAction = UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,null);
UIAlertAction okAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default,(sender)=> { handler?.Invoke(sender, new EventArgs()) ; });
alertController.AddAction(cancelAction);
alertController.AddAction(okAction);
var currentViewController = topViewControllerWithRootViewController(UIApplication.SharedApplication.Delegate.GetWindow().RootViewController);
currentViewController.PresentViewController(alertController,true,null);
}
UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
{
if (rootViewController is UITabBarController)
{
UITabBarController tabBarController = (UITabBarController)rootViewController;
return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
}
else if (rootViewController is UINavigationController)
{
UINavigationController navigationController = (UINavigationController)rootViewController;
return topViewControllerWithRootViewController(navigationController.VisibleViewController);
}
else if (rootViewController.PresentedViewController != null)
{
UIViewController presentedViewController = rootViewController.PresentedViewController;
return topViewControllerWithRootViewController(presentedViewController);
}
else
{
return rootViewController;
}
}
}
}
in Android
in MainActivity
public static MainActivity Intance;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Intance = this;
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
using Xamarin.Forms;
using xxx;
using xxx.Droid;
using Android;
using System;
using Xamarin.Forms.Platform.Android;
using Android.Support.V7.App;
using Android.Text;
[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.Droid
{
public class PopupImplemention : IPopUp
{
public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
{
// because html.string could not support format string , so you need to set the color directly in the string with a static value
Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(MainActivity.Intance);
alert.SetTitle(Html.FromHtml(string.Format("<font color='#ff0000'>{0}</font>" ,title),FromHtmlOptions.ModeLegacy));
alert.SetMessage(Html.FromHtml(string.Format("<font color='#00ff00'>{0}</font>", message), FromHtmlOptions.ModeLegacy));
alert.SetPositiveButton("OK", (senderAlert, args) =>
{
handler?.Invoke(senderAlert, args);
});
alert.SetNegativeButton("Cancel", (senderAlert, args) =>
{
});
Android.Support.V7.App.AlertDialog dialog = alert.Create();
dialog.Show();
}
}
}
And call it in forms
DependencyService.Get<IPopUp>().Popup("Title","xxxxxxxxxxxx",Color.Red,Color.Blue,(sen,args)=> {
// handle the logic when clikc the OK button
});
Option 2
You could use the plugin Rg.Plugins.Popup ,which allows to open Xamarin.Forms pages as a popup that can be shared across iOS, Android and UWP . And you can customize it as you want .
I recently changed to Xamarin Forms and notice that the title isn't centered at the top of the page for Android devices.
Is there a way that I can do this?
Here's an example of what I mean with the title:
You can use the TitleView:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TitleViewSample"
x:Class="TitleViewSample.MainPage">
<NavigationPage.TitleView>
<Label Text="Hello World" HorizontalTextAlignement="Center"/>
</NavigationPage.TitleView>
<ContentPage.Content>
<StackLayout>
<!-- Place new controls here -->
<Label Text="Welcome to Xamarin.Forms!"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
https://www.andrewhoefling.com/Blog/Post/xamarin-forms-title-view-a-powerful-navigation-view
You will have to implement ShellRenderer in this case as you have Xamarin.Forms Shell Project.
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.Support.V4.Widget;
using Android.Support.V7.Widget;
using Android.Util;
using Android.Widget;
using Japanese.Droid.CustomRenderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Toolbar = Android.Support.V7.Widget.Toolbar;
[assembly: ExportRenderer(typeof(Xamarin.Forms.Shell), typeof(MyShellRenderer))]
namespace MyProject.Droid.CustomRenderers
{
public class MyShellRenderer : ShellRenderer
{
public MyShellRenderer(Context context) : base(context)
{
}
protected override IShellToolbarAppearanceTracker CreateToolbarAppearanceTracker()
{
return new MyShellToolbarAppearanceTracker(this);
}
protected override IShellToolbarTracker CreateTrackerForToolbar(Toolbar toolbar)
{
return new MyShellToolbarTracker(this, toolbar, ((IShellContext)this).CurrentDrawerLayout);
}
}
public class MyShellToolbarAppearanceTracker : ShellToolbarAppearanceTracker
{
public MyShellToolbarAppearanceTracker(IShellContext context) : base(context)
{
}
public override void SetAppearance(Android.Support.V7.Widget.Toolbar toolbar, IShellToolbarTracker toolbarTracker, ShellAppearance appearance)
{
base.SetAppearance(toolbar, toolbarTracker, appearance);
//Change the following code to change the icon of the Header back button.
toolbar?.SetNavigationIcon(Resource.Drawable.back);
}
}
public class MyShellToolbarTracker : ShellToolbarTracker
{
public MyShellToolbarTracker(IShellContext shellContext, Toolbar toolbar, DrawerLayout drawerLayout) : base(shellContext, toolbar, drawerLayout)
{
}
protected override void UpdateTitleView(Context context, Toolbar toolbar, View titleView)
{
base.UpdateTitleView(context, toolbar, titleView);
for (int index = 0; index < toolbar.ChildCount; index++)
{
if (toolbar.GetChildAt(index) is TextView)
{
var title = toolbar.GetChildAt(index) as TextView;
//Change the following code to change the font size of the Header title.
title.SetTextSize(ComplexUnitType.Sp, 20);
toolbar.SetTitleMargin(MainActivity.displayMetrics.WidthPixels / 4 - Convert.ToInt32(title.TextSize) - title.Text.Length / 2, 0, 0, 0);
}
}
}
}
}
Here is the code for MainActivity.cs
public class MainActivity : FormsAppCompatActivity
{
public static DisplayMetrics displayMetrics;
protected override void OnCreate(Bundle savedInstanceState)
{
Window.AddFlags(WindowManagerFlags.Fullscreen);
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
displayMetrics = new DisplayMetrics();
WindowManager.DefaultDisplay.GetRealMetrics(displayMetrics);
LoadApplication(new App());
if (Window != null) Window.SetStatusBarColor(Android.Graphics.Color.Transparent);
if (isPhone(this)) RequestedOrientation = ScreenOrientation.Portrait;
}
}
As the title textview having wrapped width within toolbar not updating alignment on TextAlignment with center, you can update the layout params of the toolbar to matchparent and textview gravity as follows.
If the hamburger image added with custom image then need check that resoulution if that is too big just reduce it lower one
[assembly: ExportRenderer(typeof(MainPage), typeof(MyRenderer))]//MainPage - navigation page
namespace MyProject.Droid
{
public class MyRenderer: MasterDetailPageRenderer
{
public MyRenderer(Context context) : base(context)
{
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
var toolbar = FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
for (var i = 0; i < toolbar.ChildCount; i++)
{
var title = toolbar.GetChildAt(i) as TextView;
if (title != null && !string.IsNullOrEmpty(title.Text))
{
title.TextAlignment = Android.Views.TextAlignment.Center;
title.Gravity = GravityFlags.CenterHorizontal;
var layoutParams = (AndroidX.AppCompat.Widget.Toolbar.LayoutParams)title.LayoutParameters;
layoutParams.Width = ViewGroup.LayoutParams.MatchParent;
toolbar.RequestLayout();
}
}
}
}
}
I can change the Font Color like this:
var homePage = new NavigationPage(new HomePage())
{
Title = "Home",
Icon = "ionicons_2_0_1_home_outline_25.png",
BarTextColor = Color.Gray,
};
But is there a way to change the Font Size and Weight for the Title? I would like to change it for the iOS and Android platforms only. Hoping that someone knows of Custom Renderer code that can help me to do this.
Note that this question is similar to my question on how to change the Font which has been answered here:
How can I change the font for the header of a Navigation page with Xamarin Forms?
Here is an Custom Renderer for Android where you are able to change the Font Size and also the Font Weight. I've marked the values you have to change with an TODO.
using Android.Content;
using Android.Graphics;
using App5.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android.AppCompat;
[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationPageRenderer))]
namespace App5.Droid
{
public class CustomNavigationPageRenderer : NavigationPageRenderer
{
private Android.Support.V7.Widget.Toolbar _toolbar;
public CustomNavigationPageRenderer(Context context) : base(context)
{
}
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
if (child.GetType() == typeof(Android.Support.V7.Widget.Toolbar))
{
_toolbar = (Android.Support.V7.Widget.Toolbar)child;
_toolbar.ChildViewAdded += Toolbar_ChildViewAdded;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
}
}
private void Toolbar_ChildViewAdded(object sender, ChildViewAddedEventArgs e)
{
var view = e.Child.GetType();
System.Diagnostics.Debug.WriteLine(view);
if (e.Child.GetType() == typeof(Android.Support.V7.Widget.AppCompatTextView))
{
var textView = (Android.Support.V7.Widget.AppCompatTextView)e.Child;
// TODO: CHANGE VALUES HERE
textView.TextSize = 25;
textView.SetTypeface(null, TypefaceStyle.Bold);
_toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
}
}
}
}
Here is an implementation of a Custom Renderer for iOS.
using App5.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationPageRenderer))]
namespace App5.iOS
{
public class CustomNavigationPageRenderer : NavigationRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var att = new UITextAttributes();
// TODO: Create your FontSize and FontWeight here
var fontSize = Font.SystemFontOfSize(30.0);
var boldFontSize = Font.SystemFontOfSize(35.0, FontAttributes.Bold);
// TODO: Apply your selected FontSize and FontWeight combination here
att.Font = boldFontSize.ToUIFont();
UINavigationBar.Appearance.SetTitleTextAttributes(att);
}
}
}
}