Cesare
Cesare

Reputation: 9419

Simulate a tab bar in iOS

I have many views on top on another in a view controller, and I'm trying to simulate a tab bar. The user can tap on any button of a menu and a view will be presented according to which button was tapped. All the other views will hide.

I've written the following code, which doesn't present the views correctly (sometimes they show up, other times they don't).

presentViewWithName(.home) // this will present the view at the very bottom of the hierarchy

enum Views {
    case home
    case sketchpad
    case help
    case settings
}

func presentViewWithName(name: Views) {
    self.turnAlphaOnToEveryMenuButton()
    switch name {
    case .home:
        self.hideAllViews()
        self.menuView.buttonHome.dimmerAlpha()
    case .sketchpad:
        self.sketchpadView.animateToggleAlpha()
        self.menuView.buttonSketchpad.dimmerAlpha()
    case .help:
        self.helpView.animateToggleAlpha()
        self.menuView.buttonHelp.dimmerAlpha()
    case .settings:
        self.settingsView.animateToggleAlpha()
        self.menuView.buttonSettings.dimmerAlpha()
    }
}

func turnAlphaOnToEveryMenuButton() {
    self.menuView.buttonHome.alpha = 1
    self.menuView.buttonSketchpad.alpha = 1
    self.menuView.buttonHelp.alpha = 1
    self.menuView.buttonSettings.alpha = 1
}

func hideAllViews() {
    self.settingsView.alpha = 0
    self.sketchpadView.alpha = 0
    self.helpView.alpha = 0
}

extension UIView {
    func animateToggleAlpha() {
        UIView.animateWithDuration(0.25) {
            self.alpha = self.alpha == 1 ? 0 : 1
        }
    }

    func dimmerAlpha() {
        UIView.animateWithDuration(0.25) {
            self.alpha = self.alpha == 1 ? 0.4 : 1
        }
    }
}

I'm basically changing the alpha of the views. Say you want to present the home view. That's the view at the very bottom of the hierarchy. I just hide all the views. Say I want to present the view at the very top of the hierarchy, the settings view. I hide all the views, and then present the settings view.

How can I fix this/better do it?

Upvotes: 0

Views: 216

Answers (1)

Rajath Shetty K
Rajath Shetty K

Reputation: 424

There should be 4 views home, sketchpad, help and setting. All your view should have same super view. It should be connected to same outlet menuViews as home, sketchpad, help and setting respectively,

@IBOutlet weak var menuViews: [UIView]! 

This is your enum,

enum Views {
   case home
   case sketchpad
   case help
   case settings
}

Add function to show that view,

func presentViewWithName(name: Views) {
    UIView.animateWithDuration(0.25) {
       for (index, view) in menuViews.enumerate() {
          let  alpha = (name == (Views(rawValue: index)!)) ? 1.0 : 0.0
          view.alpha = alpha
       }
    }
}

Upvotes: 2

Related Questions