HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftMinor

Show and hide views

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andshowviewshide

Problem

I have some buttons in my class that show or hide two views (by setting their alpha property to either 0 or 1) when the user taps on them. I have written a function that uses the tag property of the sender of the button (which is passed to the function by default) to identify which view to show or hide:

@IBAction func showOrHideView(sender: AnyObject) {
    UIView.animateWithDuration(0.5, animations: {
        switch sender.tag {
        case 1:
            self.viewSketchpad.alpha = self.viewSketchpad.alpha == 1 ? 0 : 1
        case 2:
            self.viewTips.alpha = self.viewTips.alpha == 1 ? 0 : 1
        default:
            break
        }
    })
}


How can I make this code cleaner?

Solution

First, I would consider making a reusable method on UIView to encapsulate the alpha toggle:

extension UIView {

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


That way, you have a nicely encapsulated and reusable function for toggling the alpha of any view. You have already shown that you need it for two views of your app, so you will likely need it in other places.

Once you have the method above, there are two ways to make the code cleaner. If there are a bunch of views that need this behavior, and that is all the buttons are supposed to do, then you can put the views in an array and index them by the button's tag.

@IBOutlet var views: [UIView]!

@IBAction func showHideButtonTapped(sender: UIButton) {
    views[sender.tag].animateToggleAlpha()
}


If you need to do more than simply animate the views and what you need to do is different depending on which button is tapped, then I would rather see multiple methods...

@IBAction func sketchpadButtonTapped(sender: UIButton) {
    viewSketchpad.animateToggleAlpha()
    // do other stuff
}

@IBAction func tipsButtonTapped(sender: UIButton) {
    viewTips.animateToggleAlpha()
    // do different other stuff
}


Personally, the above idea (using one Action for each button) is my default unless I am assured that all the buttons have the same behavior just with different data.

Code Snippets

extension UIView {

    func animateToggleAlpha() {
        UIView.animateWithDuration(0.5) {
            self.alpha = self.alpha == 1 ? 0 : 1
        }
    }
}
@IBOutlet var views: [UIView]!

@IBAction func showHideButtonTapped(sender: UIButton) {
    views[sender.tag].animateToggleAlpha()
}
@IBAction func sketchpadButtonTapped(sender: UIButton) {
    viewSketchpad.animateToggleAlpha()
    // do other stuff
}

@IBAction func tipsButtonTapped(sender: UIButton) {
    viewTips.animateToggleAlpha()
    // do different other stuff
}

Context

StackExchange Code Review Q#129608, answer score: 4

Revisions (0)

No revisions yet.