ios - 在 Swift 中设置呈现模态的自定义大小失败——占用全屏

标签 ios iphone swift

如何让呈现模式具有自定义大小?尝试了很多不同的解决方案,其中许多似乎已经过时

这就是我从父 View Controller 实例化模态视图的方式:

self.definesPresentationContext = true
let vc = (storyboard?.instantiateViewController(withIdentifier: "modalViewController"))!
vc.modalPresentationStyle = .overCurrentContext
vc.preferredContentSize = CGSize(width: 100, height: 100)
present(vc, animated: true, completion: nil)

但是,模态视图覆盖了整个屏幕,而不是仅仅占据 100 * 100。

最佳答案

您需要实现 UIViewControllerTransitioningDelegate 方法和 UIViewControllerAnimatedTransitioning 方法来自定义呈现的 UIViewController 大小。

要知道如何实现自定义动画,

引用:https://github.com/pgpt10/Custom-Animator

编辑:

class ViewController: UIViewController
{
    //MARK: Private Properties
    fileprivate let animator = Animator()

    //MARK: View Lifecycle Methods
    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func awakeFromNib()
    {
        super.awakeFromNib()
        self.transitioningDelegate = self
        self.modalPresentationStyle = .custom
    }

    //MARK: Button Action Methods
    @IBAction func dismissController(_ sender: UIButton)
    {
        self.dismiss(animated: true, completion: nil)
    }
}

// MARK: - UIViewControllerTransitioningDelegate Methods
extension ViewController : UIViewControllerTransitioningDelegate
{
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        self.animator.transitionType = .zoom
        self.animator.size = CGSize(width: 100, height: 100)
        return self.animator
    }

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        return self.animator
    }
}

关于ios - 在 Swift 中设置呈现模态的自定义大小失败——占用全屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302590/

相关文章:

ios - 如何在 swift 中的每个循环中附加字符串

iphone - 为什么 UIScrollView 不弹跳?

iphone - UIAlertView:取消按钮应该在哪里?

iphone - 反调试怎么处理库打补丁?

iphone - 使用 GameCenter 在 iOS 中进行两人游戏

ios - 奇怪的 NavBar 在 ios 11 Xcode 9 中拉伸(stretch)

ios滚动后保持UITableViewCell布局

ios - 在显示 isModalInPresentation 设置为 true 的页面后,无法正常关闭弹出窗口

objective-c - CoreAudio AudioObjectRemovePropertyListener 在 Swift 中不起作用

swift - 在 Xcode 9 Swift 3 Watch 应用程序中安装 Alamofire