swift 将弹出窗口大小设置为当前控制器视图的大小

nvbavucw  于 2023-10-15  发布在  Swift
关注(0)|答案(1)|浏览(81)

我需要为iPhone制作一个通用的弹出框,将其大小调整为所呈现视图的大小。所以我创建了一个ViewController子类来处理所有的表示逻辑:

class PopoverViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    var contentView = UIView()

    init(contentView: UIView, sourceView: UIView) {
        super.init(nibName: nil, bundle: nil)
        self.contentView = contentView
        view = contentView
        preferredContentSize = view.bounds.size
        modalPresentationStyle = .popover
        guard let controller = popoverPresentationController else {return}
        controller.permittedArrowDirections = .up
        controller.delegate = self
        controller.sourceView = sourceView
        controller.sourceRect = sourceView.bounds
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension PopoverViewController: UIAdaptivePresentationControllerDelegate {
    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return .none
    }
}

它的大小和一切都很好,然后我设置preferredContentSize一个特定的框架(如320x260等)

但是当我将其设置为呈现的控制器的视图框或边界大小时,popover呈现默认大小:

我试图通过打印来检查contentView框架,结果发现它的宽度和高度都为零。ContentView布局代码:

override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        addSubview(titleLabel)
        addSubview(contentLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(appearance.xlSpace)
            make.leading.trailing.equalToSuperview().inset(appearance.xlSpace)
        }
        contentLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(appearance.lSpace)
            make.leading.trailing.equalToSuperview().inset(appearance.sSpace)
            make.bottom.equalToSuperview().inset(appearance.xsSpace)
        }
        print("width: \(self.bounds.width), height: \(self.bounds.height)")
    }

演示代码:

func showInfo() {
        let view = PopupView()
        let controller = PopoverViewController(contentView: view, sourceView: contentView.infoButton)
        present(controller, animated: true, completion: nil)
    }

我如何正确地设置我的popover控制器preferredContentSize来查看框架大小,并使其通用于呈现任何传入控制器的视图?

imzjd6km

imzjd6km1#

我相信问题是你设置preferredContentSize属性太早了。尝试在viewWillAppear中执行此操作。当调用init时,我不认为一切都已经正确地设置和布局了。

相关问题