Xamarin形成阻止用户后退按键

时间:2015-10-09 10:45:44

标签: xamarin xamarin.ios xamarin.android xamarin.forms

在我的Xamarin表单应用程序中,我想在用户单击主页面中的后退按钮时显示确认消息。有没有办法实现这个目标? 我在MainPage中覆盖了OnBackButtonPressed方法。但是,当按下按键时,应用程序仍在关闭。这是我的代码

protected override bool OnBackButtonPressed ()
    {
        //return base.OnBackButtonPressed ();
        return false;
    }

1 个答案:

答案 0 :(得分:3)

您可以为任何Xamarin.Form页面覆盖OnBackButtonPressed。但它只适用于Android和Windows Phone设备中的物理按钮。

    protected override bool OnBackButtonPressed () {
        DisplayAlert("title","message","ok");
        return true;
    }

对于虚拟场景,您需要创建CustomRenderers并拦截点击处理程序。在iOS中,它可能很棘手,因为用户可以返回做其他动作(例如滑动手势)。一旦你拦截它,你只需要创建你的确认消息(我假设你知道如何做)。

对于iOS,您可以执行以下操作:

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

}
}

PS您需要提供箭头图像(“图像/背面”)