Chun Wing Lean Chun Wing Lean - 5 months ago 27
Swift Question

close the table view by clicking the button with animation (swift)

I have created a tableview inside a view controller. I successfully hidden and show the table. However, it doesn't have any animation when it closes and shows the table. i want it to slide out or slide in. the following is my code.

@IBAction func clickButtonAction(sender: AnyObject) {
UIView.animateWithDuration(10.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in


}) { (finished:Bool) -> Void in
if(self.tableView.hidden == true){
self.tableView?.hidden = false
}
else{
self.tableView.hidden = true
}
}

}

Answer

You can't animated the hidden property of UIView. You have to animate the alpha property between 0.0 and 1.0 instead. You're also doing your work in the completion block of your animation. You should be doing it in the animations block. I also cleaned up the code a little bit. I'm assuming that tableView is declared as UITableView?, but if it's UITableView or UITableView, you can omit the ? when accessing it:

@IBAction func clickButtonAction(sender: AnyObject) {
    UIView.animateWithDuration(10.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
        if self.tableView?.alpha == 1.0 {
            self.tableView?.alpha = 0.0
        }
        else {
            self.tableView?.alpha = 1.0
        }
    }, completion: { (finished:Bool) -> Void in

    })
}

Note: you may not want to directly compare alpha == 1.0, since floating point math is hard. Instead, I recommend keeping a local variable, using that to track state, and then base your alpha off of that:

// Make sure this matches the initial hidden state of your table view.
// So if your table view starts at alpha == 0.0, this should be true.
private var tableViewHidden: Bool = false

@IBAction func clickButtonAction(sender: AnyObject) {
    tableViewHidden = !tableViewHidden
    UIView.animateWithDuration(10.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
        if tableViewHidden {
            self.tableView?.alpha = 0.0
        }
        else {
            self.tableView?.alpha = 1.0
        }
    }, completion: { (finished:Bool) -> Void in

    })
}
Comments