如何在自定义大小中显示一个模态视图控制器?

我想用底部的animation呈现一个自定义大小的模式视图控制器。 我可以使用ModalPresentationStyle实现这个animation到FormSheet ,但是它迫使我使用540×620的默认尺寸,而且我的视图不适合。

我该如何做一个类似的过渡到一个任意大小的视图(控制器)放置在屏幕的中心?

我没有find一种方法来从模态控制器本身,所以我创build了一个类和一个扩展方法:

 public class ModalViewController : UIViewController { public SizeF OriginalViewSize { get; private set; } void Initialize () { ModalPresentationStyle = UIModalPresentationStyle.FormSheet; } public override void ViewDidLoad () { OriginalViewSize = View.Bounds.Size; base.ViewDidLoad (); } public ModalViewController (IntPtr handle) : base (handle) { Initialize (); } public ModalViewController (string nibName, NSBundle bundle) : base (nibName, bundle) { Initialize (); } public ModalViewController () : base () { Initialize (); } } public static class ModalViewControllerExtensions { public static void PresentModalViewController (this UIViewController parent, ModalViewController target) { parent.PresentViewController (target, true, null); target.View.Superview.AutoresizingMask = UIViewAutoresizing.FlexibleMargins; target.View.Superview.Frame = new RectangleF (PointF.Empty, target.OriginalViewSize); target.View.Superview.Center = UIScreen.MainScreen.Bounds.Center ().Rotate (); } } 

这大概是我如何使用它:

 this.PresentModalViewController ( new PublishModalViewController (Item, HandlePublishAction) ); 

我不需要明确地指定大小,这很方便,因为它使用来自界面构build器的根视图边界。 我不确定这是如何反应自动旋转,它可能需要一些调整。 我也在这里使用两种扩展方法:

 public static PointF Rotate (this PointF pt) { return new PointF (pt.Y, pt.X); } public static PointF Center (this RectangleF rect) { return new PointF ( (rect.Right - rect.Left) / 2.0f, (rect.Bottom - rect.Top) / 2.0f ); } 

这就是它。

更简单的方法如下

将模态视图控制器作为一个表单并在模态视图控制器中添加:

 public override void ViewWillLayoutSubviews () { base.ViewWillLayoutSubviews (); this.View.Superview.Bounds = new RectangleF (0, 0, 900, 700); } 

如果您不想让ios指定默认表单大小,则设置所需的宽度和高度非常重要

更新:在ios 8中至less有上面的解决schemetriggeres一个无限循环的情况。 看起来在某些情况下(比如当在模式视图中embeddedwebview并在某些htmlinput文本中点击),更改超级视图边界会触发模态视图的布局,从而导致应用程序的无限循环和冻结。 但在ios 8中,您可以简单地设置PrefferedSize属性来达到相同的效果。