Xamarin iOS应用旋转时,Xamarin Community Toolkit弹窗无法居中
Xamarin iOS中XCT Popup横屏偏移的修复方案
在iOS平台,当Xamarin Community Toolkit的Popup已打开时切换横屏,会出现弹窗偏移到左上角的问题,这是因为iOS端默认未监听屏幕旋转事件来重新计算弹窗位置。以下是两种可行的修复方法:
方法一:自定义iOS渲染器
在iOS项目中创建自定义渲染器,监听设备旋转并重置弹窗中心:
using Xamarin.CommunityToolkit.UI.Views; using Xamarin.CommunityToolkit.UI.Views.iOS; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(NewPopup), typeof(CenteredPopupRenderer))] namespace Mobile.iOS.Renderers { public class CenteredPopupRenderer : PopupRenderer { public CenteredPopupRenderer() { UIDevice.CurrentDevice.OrientationDidChange += OnOrientationChanged; } private void OnOrientationChanged(object sender, System.EventArgs e) { if (Element == null || View == null) return; var screenBounds = UIScreen.MainScreen.Bounds; View.Center = new CoreGraphics.CGPoint(screenBounds.GetMidX(), screenBounds.GetMidY()); } protected override void Dispose(bool disposing) { if (disposing) { UIDevice.CurrentDevice.OrientationDidChange -= OnOrientationChanged; } base.Dispose(disposing); } } }
方法二:在Popup后台代码中调整布局
在NewPopup.xaml.cs中订阅SizeChanged事件,手动计算并更新弹窗位置:
using Xamarin.CommunityToolkit.UI.Views; using Xamarin.Forms; namespace Mobile { public partial class NewPopup : Popup { public NewPopup() { InitializeComponent(); SizeChanged += OnPopupSizeChanged; } private void OnPopupSizeChanged(object sender, System.EventArgs e) { if (Device.RuntimePlatform != Device.iOS) return; var mainPage = Application.Current.MainPage; var newX = (mainPage.Width - Size.Width) / 2; var newY = (mainPage.Height - Size.Height) / 2; LayoutTo(new Rectangle(newX, newY, Size.Width, Size.Height)); } } }
注意事项
- 两种方法都能解决旋转后的居中问题,渲染器方案更贴近原生层,稳定性更高;
- 确保
NewPopup类的访问级别为public,否则渲染器无法识别; - 测试时需验证弹窗打开状态下旋转屏幕的场景。
内容的提问来源于stack exchange,提问作者abani samal
相关产品推荐
相关产品推荐

