ios - 如何创建一个只有屏幕一半高度的 ViewController?

标签 ios swift

我想要 pageSheet UIModalPresentationStyle segue 的所有功能,但我只希望呈现的 ViewController 显示一半屏幕(参见下图中的示例)。

enter image description here

我使用 pageSheet modalPresentationStyle 以模态方式呈现它,但它总是以 100% 的高度呈现它。

我无法弄清楚如何限制或修改 ViewController 的高度。我在 SecondViewController 中尝试了以下操作,但没有成功:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.preferredContentSize = CGSize(width: self.view.frame.width, height: 400)
    }
} 

我正在使用 Storyboard Segues 和一个以模态方式呈现它的按钮来启动 segue:
enter image description here

最佳答案

我想出了一种方法来做到这一点,我发现这很简单:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let newView = UIView(frame: CGRect(x: 0, y: 500, width: self.view.frame.width, height: 400))
        newView.backgroundColor = .yellow
        newView.layer.cornerRadius = 20

        self.view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))

        // self.view is now a transparent view, so now I add newView to it and can size it however, I like.

        self.view.addSubview(newView)


        // works without the tap gesture just fine (only dragging), but I also wanted to be able to tap anywhere and dismiss it, so I added the gesture below
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        self.view.addGestureRecognizer(tap)
    }

    @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
        dismiss(animated: true, completion: nil)
    }
}

关于ios - 如何创建一个只有屏幕一半高度的 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61598724/

相关文章:

objective-c - 与 AVPlayer 的帧同步

javascript - 我如何监控 WKWebview 上的请求?

ios - [iOS]KVO setValuesForKeysWithDictionary

ios - 如何在 Swift 中将旋转速度降低到 0?

ios - 动画约束快速适合所有屏幕

swift - 使用 Swift 4 Codable PropertyListDecoder() 解码 PropertyList

ios - 在文本字段中显示 XML 元素的数量

ios - 如何使用 swift 作为 postman 请求测试来使用行 http 正文发出发布请求?

ios - 如何创建圆形和三角形按钮

ios - Swift:从 xib 以编程方式创建 UIViewController