UIKit Missing Bits #1
Some Handy Utilities
April 03, 2015
Just a quick post today. Here are some UIKit bits that should have always existed but after 8 years are still absent:
setHidden:animated:
- Absolutely inexcusable that we still have basicUIView
properties that can't be animatedsetEnabled:animated:
- Ditto forUIControl
setEnabled:animated:
- For some inexplicable reason, UIBarButtonItems hide the fact that they are views which complicates the animation story slightly.animated
- This one is a handy Swift method. When used with trailing closure syntax, it makes it trivial to implement logic that needs to fire animated or non-animated depending on some condition.
extension UIView {
func setHidden(wantsHidden:Bool, animated:Bool) {
if self.hidden == wantsHidden {
return
}
if !animated {
self.hidden = wantsHidden
return
}
if wantsHidden {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.alpha = 0.0
}, completion: { (completed) -> Void in
self.alpha = 1.0
self.hidden = true
})
}
else {
self.alpha = 0.0
self.hidden = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.alpha = 1.0
})
}
}
func animated(animated:Bool, f:()->()) {
if animated {
f()
}
else {
UIView.setAnimationsEnabled(false)
f()
UIView.setAnimationsEnabled(true)
}
}
}
extension UIControl {
func setEnabled(wantsEnabled:Bool, animated:Bool) {
UIView.transitionWithView(self.superview!,
duration: 0.5,
options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: { () -> Void in
self.enabled = wantsEnabled
}, completion:nil)
}
}
extension UIBarButtonItem {
func setEnabled(wantsEnabled:Bool, animated:Bool) {
if let superView = (self as AnyObject).view? {
UIView.transitionWithView(superView,
duration: 0.5,
options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: { () -> Void in
self.enabled = wantsEnabled
}, completion:nil)
}
else {
self.enabled = wantsEnabled
}
}
}
What are some of your favorite missing bits?
Russ Bishop
This blog represents my own personal opinion and is not endorsed by my employer.