본문 바로가기
Programming/Swift

[Readable Coding Practice] How to make swiping view controller with swiping menu tab bar

by Eisen Sophie 2021. 8. 1.

You can make swiping views with swiping menu bar by using collectionviews.

 

This is the viewcontroller that app starts with.

 

import UIKit

class BaseViewController: UICollectionViewController {
    
    let menuBar: MenuBar = {
       let menuBar = MenuBar()
        //menuBar.vc = self
        menuBar.translatesAutoresizingMaskIntoConstraints = false
        return menuBar
    }()
    
    let backgroundColor: [UIColor] = [.brown, .blue, .darkGray, .red]
    
    let labelString = ["House", "Pencil", "Person", "Circle"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationController?.navigationBar.isTranslucent = false
        
        configureNavigationTitleLabel()
        configureCollectionView()
        configureMenuBar()
    }

    fileprivate func configureNavigationTitleLabel() {
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height))
        titleLabel.text = "iFinance"
        titleLabel.textColor = .white
        titleLabel.font = UIFont.boldSystemFont(ofSize: 32)
        navigationItem.titleView = titleLabel
    }
    
    fileprivate func configureCollectionView() {
        collectionView.backgroundColor = .systemBackground
        collectionView.register(BaseViewCell.self, forCellWithReuseIdentifier: BaseViewCell.identifier)
        collectionView.isPagingEnabled = true
        
        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }
    }
    
    fileprivate func configureMenuBar() {
        menuBar.vc = self
        view.addSubview(menuBar)
        
        NSLayoutConstraint.activate([
            menuBar.topAnchor.constraint(equalTo: view.topAnchor),
            menuBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            menuBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            menuBar.heightAnchor.constraint(equalToConstant: 50),
        ])
    }
    
    func scrollToMenuIndex(menuIndex: Int){
        collectionView.isPagingEnabled = false
        let indexPath = IndexPath(row: menuIndex, section: 0)
        collectionView.scrollToItem(at: indexPath, at: [], animated: true)
        collectionView.isPagingEnabled = true
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        4
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BaseViewCell.identifier, for: indexPath) as! BaseViewCell
        
        cell.backgroundColor = backgroundColor[indexPath.item]
        cell.set(labelString: labelString[indexPath.item])
        
        return cell
    }
}

extension BaseViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        .init(width: view.frame.width, height: view.frame.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        0
    }
}

On this viewcontroller, there are two collectionviews that are scrollerable horizontally.

 

This is MenuTabBarView that is attached under nav bar.

import UIKit

class MenuTabBarView: UIView {
    
    let collectionView: UICollectionView = {
        let cv = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        cv.backgroundColor = .systemBlue
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()
    
    var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?
    
    var vc: BaseViewController?
    
    let cellImageString = ["house", "pencil", "person", "circle"]
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configureCollectionView()
        configureHorizontalBar()
    }
    
    fileprivate func configureCollectionView() {
        collectionView.register(MenuBarCell.self, forCellWithReuseIdentifier: MenuBarCell.identifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        addSubview(collectionView)
        
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: topAnchor),
            collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
    
    fileprivate func configureHorizontalBar() {
        let horizontalBar = UIView()
        horizontalBar.translatesAutoresizingMaskIntoConstraints = false
        horizontalBar.backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        addSubview(horizontalBar)
        
        horizontalBarLeftAnchorConstraint = horizontalBar.leftAnchor.constraint(equalTo: self.leftAnchor)
        
        horizontalBarLeftAnchorConstraint?.isActive = true
        
        NSLayoutConstraint.activate([
            horizontalBar.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            horizontalBar.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1 / 4),
            horizontalBar.heightAnchor.constraint(equalToConstant: 3)
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension MenuTabBarView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        4
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MenuBarCell.identifier, for: indexPath) as! MenuBarCell
        cell.cellImageView.image = UIImage(systemName: cellImageString[indexPath.item])
        return cell
    }
}

extension MenuTabBarView: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        vc?.scrollToMenuIndex(menuIndex: indexPath.item)
    }
}

extension MenuTabBarView: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        .init(width: frame.width/4, height: frame.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        0
    }
}

 

The collectionviews in MenuTabBarView and baseViewcontroller need to be able to communicate each other, so that whenever one of them moves, the another can move asynchronously.

 

 

In order for them to communicate, you need to consider two scenarios.

The first is when the user scroll base view, the another case is when the user tab one of items on MenuTabBarView.

 

For the first scenario I used following code in BaseViewController.

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
    }

 

For the Second scenario,

 

I used this code in MenuTabBarView class

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        baseViewController?.scrollToMenuIndex(menuIndex: indexPath.item)
    }

scrollToMenuIndex function is locating in baseViewController,

so that collectionview item in BaseViewController can be modified directly. 

func scrollToMenuIndex(menuIndex: Int){
        collectionView.isPagingEnabled = false
        let indexPath = IndexPath(row: menuIndex, section: 0)
        collectionView.scrollToItem(at: indexPath, at: [], animated: true)
        collectionView.isPagingEnabled = true
    }

 

 

 

 

 

 

FULL CODES

 

SceneDelegate

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        
        //change nav bar color
        UINavigationBar.appearance().barTintColor = .systemBlue
        
        //enliminate nav bar shadow
        UINavigationBar.appearance().shadowImage = UIImage()
        
        window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        window?.windowScene = windowScene
        
        window?.rootViewController = UINavigationController(rootViewController: BaseViewController(collectionViewLayout: UICollectionViewFlowLayout())) 
        window?.makeKeyAndVisible()
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}

 

 

BaseViewController

import UIKit

class BaseViewController: UICollectionViewController {
    
    let menuBar: MenuTabBarView = {
       let menuBar = MenuTabBarView()
        menuBar.translatesAutoresizingMaskIntoConstraints = false
        return menuBar
    }()
    
    let backgroundColor: [UIColor] = [.brown, .blue, .darkGray, .red]
    
    let labelString = ["House", "Pencil", "Person", "Circle"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationController?.navigationBar.isTranslucent = false
        
        configureNavigationTitleLabel()
        configureCollectionView()
        configureMenuBar()
    }

    fileprivate func configureNavigationTitleLabel() {
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height))
        titleLabel.text = "iFinance"
        titleLabel.textColor = .white
        titleLabel.font = UIFont.boldSystemFont(ofSize: 32)
        navigationItem.titleView = titleLabel
    }
    
    fileprivate func configureCollectionView() {
        collectionView.backgroundColor = .systemBackground
        collectionView.register(BaseViewCell.self, forCellWithReuseIdentifier: BaseViewCell.identifier)
        collectionView.isPagingEnabled = true
        
        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }
    }
    
    fileprivate func configureMenuBar() {
        menuBar.baseViewController = self
        view.addSubview(menuBar)
        
        NSLayoutConstraint.activate([
            menuBar.topAnchor.constraint(equalTo: view.topAnchor),
            menuBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            menuBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            menuBar.heightAnchor.constraint(equalToConstant: 50),
        ])
    }
    
    func scrollToMenuIndex(menuIndex: Int){
        collectionView.isPagingEnabled = false
        let indexPath = IndexPath(row: menuIndex, section: 0)
        collectionView.scrollToItem(at: indexPath, at: [], animated: true)
        collectionView.isPagingEnabled = true
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        menuBar.horizontalBarLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        4
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BaseViewCell.identifier, for: indexPath) as! BaseViewCell
        
        cell.backgroundColor = backgroundColor[indexPath.item]
        cell.set(labelString: labelString[indexPath.item])
        
        return cell
    }
}

extension BaseViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        .init(width: view.frame.width, height: view.frame.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        0
    }
}

 

MenuTabBar

import UIKit

class MenuTabBarView: UIView {
    
    let collectionView: UICollectionView = {
        let cv = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        cv.backgroundColor = .systemBlue
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()
    
    var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?
    
    var baseViewController: BaseViewController?
    
    let cellImageString = ["house", "pencil", "person", "circle"]
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configureCollectionView()
        configureHorizontalBar()
    }
    
    fileprivate func configureCollectionView() {
        collectionView.register(MenuBarCell.self, forCellWithReuseIdentifier: MenuBarCell.identifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        addSubview(collectionView)
        
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: topAnchor),
            collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
    
    fileprivate func configureHorizontalBar() {
        let horizontalBar = UIView()
        horizontalBar.translatesAutoresizingMaskIntoConstraints = false
        horizontalBar.backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        addSubview(horizontalBar)
        
        horizontalBarLeftAnchorConstraint = horizontalBar.leftAnchor.constraint(equalTo: self.leftAnchor)
        
        horizontalBarLeftAnchorConstraint?.isActive = true
        
        NSLayoutConstraint.activate([
            horizontalBar.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            horizontalBar.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1 / 4),
            horizontalBar.heightAnchor.constraint(equalToConstant: 3)
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension MenuTabBarView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        4
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MenuBarCell.identifier, for: indexPath) as! MenuBarCell
        cell.cellImageView.image = UIImage(systemName: cellImageString[indexPath.item])
        return cell
    }
}

extension MenuTabBarView: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        baseViewController?.scrollToMenuIndex(menuIndex: indexPath.item)
    }
}

extension MenuTabBarView: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        .init(width: frame.width/4, height: frame.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        0
    }
}

 

MenuBarCell

import UIKit

class MenuBarCell: UICollectionViewCell {
    static let identifier = "MenuBarCell"
    
    let cellImageView: UIImageView = {
       let imageView = UIImageView()
        imageView.tintColor = .white
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(cellImageView)
        
        NSLayoutConstraint.activate([
            cellImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            cellImageView.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

 

BaseViewCell

import UIKit

class BaseViewCell: UICollectionViewCell{
    static let identifier = "BaseViewCell"
    
    let label: UILabel = {
       let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: .zero)
        configureLabel()
    }
    
    fileprivate func configureLabel(){
        addSubview(label)
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: centerXAnchor),
            label.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func set(labelString: String) {
        label.text = labelString
    }
}