Monday, March 11, 2019

Slide-in Subview in Swift

I'm developing a pet project, and I want to make a slide-in subview as shown in the image below.


1. Adding the slide-in view and animate it


@IBAction func historyButtonTouched(_ sender: HistoryButton) {
        
        if historyPopupHidden() {
            buttonsStackView.addSubview(historyPopupBackground!) // add and bring to front
            historyPopupBackground?.leadingAnchor.constraint(equalTo: buttonsStackView.leadingAnchor).isActive = true
            historyPopupBackground?.trailingAnchor.constraint(equalTo: buttonsStackView.trailingAnchor).isActive = true
            historyPopupBackground?.topAnchor.constraint(equalTo: buttonsStackView.topAnchor).isActive = true
            historyPopupBackground?.bottomAnchor.constraint(equalTo: buttonsStackView.bottomAnchor).isActive = true
            historyPopupBackground?.translatesAutoresizingMaskIntoConstraints = false

            buttonsStackView.addSubview(historyPopup!) // add and bring to front
            historyPopup?.leadingAnchor.constraint(equalTo: buttonsStackView.leadingAnchor).isActive = true
            historyPopup?.topAnchor.constraint(equalTo: buttonsStackView.topAnchor).isActive = true
            historyPopup?.bottomAnchor.constraint(equalTo: buttonsStackView.bottomAnchor).isActive = true
            historyPopup?.widthAnchor.constraint(equalToConstant: 280).isActive = true
            historyPopup?.translatesAutoresizingMaskIntoConstraints = false
            
            let tx = (historyPopup?.frame.width)!
            historyPopup?.transform = CGAffineTransform(translationX: -1 * tx, y: 0)
            UIView.animate(withDuration: 0.3, animations: {
                self.historyPopup?.transform = (self.historyPopup?.transform.translatedBy(x: tx, y: 0))!
            })
        } else {
            hideHistoryPopup()
        }
}
 

The historyPopup view is loaded from a nib file in viewDidLoad() method. The historyPopupBackground is just a custom UIView with a transparent black background and is initialized in viewDidLoad() as well. Read here to understand what CGAffineTransform is for.

2. Removing the subview



private func hideHistoryPopup() {
        let tx = (historyPopup?.frame.width)!

        UIView.animate(withDuration: 0.3, animations: {
            self.historyPopup?.transform = (self.historyPopup?.transform.translatedBy(x: -1 * tx, y: 0))!
        }, completion: { (finished: Bool) in
            if finished {
                self.historyPopup?.removeFromSuperview()
                self.historyPopupBackground?.removeFromSuperview()
            }
        })
}
 




No comments:

Post a Comment