You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MvvmCross框架下iOS端实现非全屏自定义Dialog弹窗求助

解决方案

最简便的实现方式不需要自定义MvvmCross的Presenter,仅需修改你现有ViewController的布局逻辑即可,完全复用你已有的ViewModel层代码,不会出现断言报错问题。

核心改动逻辑

  • 保留你现有UIModalPresentationStyle.OverFullScreen的配置,这是iPhone端实现自定义非全屏弹窗的基础
  • 将弹窗根视图的背景改为半透明蒙层,替代原有的白色背景,透出下层页面内容
  • 取消弹窗容器formView的全屏约束,改为固定尺寸居中展示

修改后完整iOS View代码

[MvxModalPresentation(WrapInNavigationController = false,
    ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve,
    ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen)]
class MessageDialogView : MvxViewController<MessageDialogViewModel>
{
    public override void ViewDidLoad()
    {
        // 根视图改为半透明蒙层,透出下层页面
        View.BackgroundColor = UIColor.Black.ColorWithAlpha(0.5f);
        base.ViewDidLoad();

        var formView = new UIView();
        formView.BackgroundColor = UIColor.Black;
        // 可选:加圆角和Android端弹窗效果对齐
        formView.Layer.CornerRadius = 12f;
        formView.ClipsToBounds = true;

        var message = new UILabel() { Text = ViewModel.Message };
        formView.Add(message);
        message.TextColor = UIColor.White;
        message.Font = message.Font.WithSize(20f);
        message.Lines = 0; // 支持多行文本自动换行

        var btnClose = new UIButton(UIButtonType.RoundedRect);
        btnClose.SetTitle("Close", UIControlState.Normal);
        btnClose.Font = btnClose.Font.WithSize(20f);
        btnClose.SetTitleColor(UIColor.Clear.FromHex(0x00D0F7), UIControlState.Normal);
        formView.Add(btnClose);

        var set = this.CreateBindingSet<MessageDialogView, MessageDialogViewModel>();
        set.Bind(btnClose).To(vm => vm.CloseCommand);
        // 可选:点击半透明蒙层也关闭弹窗,可解除下面注释
        // var tapGesture = new UITapGestureRecognizer();
        // set.Bind(tapGesture).To(vm => vm.CloseCommand);
        // View.AddGestureRecognizer(tapGesture);
        set.Apply();

        View.Add(formView);

        View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
        formView.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();

        // formView不再撑满全屏,改为固定宽度、居中显示
        View.AddConstraints(
            formView.WithSameCenterX(View),
            formView.WithSameCenterY(View),
            formView.Width().EqualTo(300f),
            // 小屏设备自动适配宽度,左右留20dp边距避免溢出
            formView.Width().LessThanOrEqualTo(View.Width()).Minus(40f)
        );

        formView.AddConstraints(
            message.AtTopOf(formView, 20f),
            message.AtLeftOf(formView, 16f),
            message.AtRightOf(formView, 16f),

            btnClose.Below(message, 20f),
            btnClose.AtRightOf(formView, 16f),
            btnClose.AtBottomOf(formView, 16f)
        );
    }
}

内容的提问来源于stack exchange,提问作者Jim Wilcox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:36:03