Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

ios - How to present a modal view controller with custom size in center?

I want to present a custom-sized modal view controller with animation from the bottom. I can achieve this animation with ModalPresentationStyle to FormSheet, but it forces me to use the default size which is 540x620 and my view doesn't fit.

How do I make perform a similar transition to an arbitrarily sized view (controller) placed in center of the screen?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I didn't find a way to do it from the modal controller itself so I created a class and an extension method:

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 is roughly how I use it:

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

It is convenient that I don't need to specify the size explicitly because it uses root View's bounds from the interface builder. I'm not sure how this reacts to autorotate, it may need some tuning. I'm also using two extension methods here:

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

And this is it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...