Skip to content

Instantly share code, notes, and snippets.

@fuxingloh
Last active November 15, 2015 06:34
Show Gist options
  • Select an option

  • Save fuxingloh/870e403278935132449e to your computer and use it in GitHub Desktop.

Select an option

Save fuxingloh/870e403278935132449e to your computer and use it in GitHub Desktop.
iOS Swift: Group buttons together?
class ButtonGroup{
let buttons: [UIButton]
let defaultBackgroundColor: UIColor?
let defaultTitleColor: UIColor?
let unSelectable: Bool
let activeBackgroundColor: UIColor
let activeTitleColor: UIColor
var lastClickedButton: UIButton?
init(buttons: [UIButton], activeBackground: UIColor, activeTitle: UIColor, unSelectable: Bool = false){
self.activeBackgroundColor = activeBackground
self.activeTitleColor = activeTitle
self.buttons = buttons
self.unSelectable = unSelectable
self.defaultBackgroundColor = buttons[0].backgroundColor
self.defaultTitleColor = buttons[0].titleColorForState(.Normal)
}
func didTouchUpInside(button: UIButton!){
for button in buttons{
button.backgroundColor = defaultBackgroundColor
button.setTitleColor(defaultTitleColor, forState: .Normal)
}
if (lastClickedButton == nil || unSelectable || lastClickedButton != button){
button.backgroundColor = activeBackgroundColor
button.setTitleColor(activeTitleColor, forState: .Normal)
lastClickedButton = button
}else{
lastClickedButton = nil
}
}
class func group(buttons: [UIButton], activeBackground: UIColor, activeTitle: UIColor) -> ButtonGroup{
return ButtonGroup(buttons: buttons, activeBackground: activeBackground, activeTitle: activeTitle)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment