4
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ How can I connect 'views' outlet in storyboard , or to where should I connect that 'views' IBOutlet? \$\endgroup\$
    – Anees
    Commented Jun 4, 2019 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.