The Code Structure for Xamarin Forms to Add the Block User Back Key Press Functionality

xam-forms-nav-bar-back-button-click-override

If you are building a cross-platform mobile application using the Xamarin app development technology and are facing any trouble, in addition, to implementing code to send a confirmation message to the mobile screens of the users when they click on the back button of the mobile devices from the main page of the app.

A lot of developers are using the button override function as OnBackButtonPressed on the main page of their Xamarin.Forms project, but only works well on the Android and Windows devices. While they get in trouble when they want to implement similar functionality in the Xamarin for iOS. Hence, this code will help them a lot:

[assembly: ExportRenderer (typeof (YourPage), typeof (YourPageRenderer))]

namespace YourNamespace {

public class YourPageRenderer : PageRenderer {

public override void ViewWillAppear (bool animated) {

base.ViewWillAppear (animated);

Action goBack = () => page.DisplayAlert(“title”,”message”,”ok”);

var backButton = new NavBackButton (goBack);

navigationItem.LeftBarButtonItem = new UIBarButtonItem (backButton);

}

}

public class NavBackButton : UIView {

public NavBackButton (Action onButtonPressed) {

SetButton (onButtonPressed);

}

UILabel text;

UIImageView arrow;

void SetButton(Action onButtonPressed){

arrow = new UIImageView(new CGRect(-25,0, 50, 50)) {

Image = new UIImage(“Images/back”).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

};

arrow.TintColor = Colors.DarkGreen.ToUIColor ();

text = new UILabel(new CGRect(arrow.Frame.Width + arrow.Frame.X -15, arrow.Frame.Height /2 – 10, 40, 20))  { Text = “Back” };

text.TextColor = Colors.DarkGreen.ToUIColor ();

Frame = new CGRect(0,0,text.Frame.Size.Width + arrow.Frame.Width, arrow.Frame.Height);

AddSubviews (new UIView[] { arrow, text });

var tapGesture = new UITapGestureRecognizer (onButtonPressed);

AddGestureRecognizer (tapGesture);

}

public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt) {

base.TouchesBegan (touches, evt);

text.TextColor =  UIColor.YourColor;

arrow.TintColor =  UIColor.YourColor;

}

public override void TouchesEnded (Foundation.NSSet touches, UIEvent evt){

base.TouchesEnded (touches, evt);

arrow.TintColor = UIColor.YourColor;

text.TextColor = UIColor.YourColor;

}

}

}

For more useful codes like this, keep visiting and reading the blogs of Hire Xamarin Developers.

by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>