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

.NET MAUI中如何将键盘纳入安全区域(SafeArea)

在.NET MAUI中启用iOS键盘推视图的默认行为

要让iOS端的键盘自动推动视图(而非覆盖输入框),需要通过.NET MAUI的平台特定代码调用iOS原生API,具体实现方式如下:

方法一:全局设置(所有页面生效)

在iOS项目的Platforms/iOS/AppDelegate.cs文件中,修改FinishedLaunching方法,配置视图控制器的自动调整属性:

using UIKit;

namespace YourAppName.iOS;

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        var result = base.FinishedLaunching(application, launchOptions);
        
        // 全局启用键盘适配行为
        UIViewController.DefaultViewControllerPresentationHandler = viewController =>
        {
            // 启用滚动视图内边距自动调整(兼容旧版iOS)
            viewController.AutomaticallyAdjustsScrollViewInsets = true;
            
            // 针对iOS 11及以上版本,设置滚动视图的内边距调整策略
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                foreach (var subview in viewController.View.Subviews)
                {
                    if (subview is UIScrollView scrollView)
                    {
                        scrollView.ContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.Automatic;
                    }
                }
            }
        };

        return result;
    }
}

方法二:单个页面设置(仅目标页面生效)

如果只需特定页面启用该行为,可在共享项目的页面代码中添加平台特定逻辑:

#if IOS
using UIKit;
using Microsoft.Maui.Platform;
#endif

namespace YourAppName.Views;

public partial class YourTargetPage : ContentPage
{
    public YourTargetPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
#if IOS
        // 获取当前页面对应的iOS视图控制器
        if (Handler?.PlatformView is UIViewController viewController)
        {
            viewController.AutomaticallyAdjustsScrollViewInsets = true;
            
            // 遍历子视图,配置滚动视图的内边距调整
            foreach (var subview in viewController.View.Subviews)
            {
                if (subview is UIScrollView scrollView)
                {
                    scrollView.ContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.Automatic;
                }
            }
        }
#endif
    }
}

关键说明

  • AutomaticallyAdjustsScrollViewInsets:控制视图控制器是否自动调整其内部滚动视图的内边距,以适配键盘弹出。
  • UIScrollViewContentInsetAdjustmentBehavior.Automatic:iOS 11+的替代属性,确保滚动视图根据安全区域和键盘位置自动调整内边距,实现视图被键盘推动的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:22:06