简单的滑动关闭,支持自动布局和动态高度

小组主讲人

向视图控制器添加滑动-关闭逻辑,支持自动布局和动态高度。

图像

Installation

Add this package to your project by searching .https://github.com/PimCoumans/PanelPresenter

To make use of the behavior that provides, make sure your view controller conforms to and set the presenter‘s property to in your initializer. Doing this at a later stage will result in weird stuff.PanelPresenterPanelPresentableviewControllerself

class SimpleViewController: UIViewController, PanelPresentable {
    
    let panelPresenter = PanelPresenter()
    
    init() {
        super.init(nibName: nil, bundle: nil)
        panelPresenter.viewController = self
    }
}

Just add your views to your , which will be added to ‘s scroll view. And any navigation-type views can be placed in the which will be displayed above your content and will stick to the top of the screen when scrolling.viewpanelPresenterheaderContentView

    private lazy var simpleView: UIView = {
        let view = UIView()
        view.backgroundColor = .systemMint
        return view
    }()
    
    private lazy var cancelButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Cancel", for: .normal)
        button.addAction(UIAction { [unowned self] _ in
            self.presentingViewController?.dismiss(animated: true)
        }, for: .touchUpInside)
        return button
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.tintColor = .black
        
        view.addSubview(simpleView)
        topContentView.addSubview(cancelButton)
        
        simpleView.translatesAutoresizingMaskIntoConstraints = false
        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            simpleView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            simpleView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            simpleView.topAnchor.constraint(equalTo: view.topAnchor),
            simpleView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            simpleView.heightAnchor.constraint(equalToConstant: 200),
            
            cancelButton.leadingAnchor.constraint(equalTo: topContentView.layoutMarginsGuide.leadingAnchor),
            cancelButton.centerYAnchor.constraint(equalTo: topContentView.layoutMarginsGuide.centerYAnchor)
        ])
    }

Example code

Check the sample app in the repository to see multiple supported scenarios for presenting your view as a panel, the simplest being comparable to the example shown above. A more complex example is where a bunch of random, multiline labels are dynamically added to a . The height animates whenever the a label is added or removed. In the method an example is shown how to animate the height change by wrapping in an animation closure.StackViewControllerUIStackViewanimateChanges()panelPresenter.layoutIfNeeded()

Questions?

Look me up on twitter! ✌🏻

GitHub

点击跳转