I have ten buttons in a slide out menu. How do I change the text color of the ten buttons from black to white by selection and then revert back to the original state when a user clicks on another button.
I am looping through the buttons one by one and I used the code
@IBAction func onBtnClick(sender: UIButton) {
hmImg.hidden = true
editprofileImg.hidden = true
cntctsReqImg.hidden = true
cntctsManImg.hidden = true
preferencesImg.hidden = true
timeRuleImg.hidden = true
helpImg.hidden = true
logoutImg.hidden = true
var a: NSInteger = sender.tag
if a == 1
{
homeBtn.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)
hmImg.hidden = false
}
else if a == 2
{
editProfileBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
editprofileImg.hidden = false
}
else if a == 3
{
cntctsRequetsBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
cntctsReqImg.hidden = false
}
else if a == 4
{
cntctMangBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
cntctsManImg.hidden = false
}
else if a == 5
{
preferenceBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
preferencesImg.hidden = false
}
else if a == 6
{
timeruleBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
timeRuleImg.hidden = false
}
else if a == 7
{
helpBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
helpImg.hidden = false
}
else if a == 8
{
logoutBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
logoutImg.hidden = false
}
the problem with this state is the button color remains white when I select other buttons. I want to change the text color to black when a user selects another button
control state for selection is hardly present for a few seconds when I click on the button
Try this:
let buttons = [homeBtn, editProfileBtn, ...]
let images [hmImg, ....]
func selectItemAtIndex(index:Int) {
buttons.forEach {
$0.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
}
images.forEach {
$0.hidden = true
}
buttons[index].setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
images[index].hidden = false
}
@IBAction func onBtnClick(sender: UIButton) {
let index = sender.tag
selectItemAtIndex(index - 1) // your tags is 1 based.
}
Or you may use a different way which involves less looping.
let images [hmImg, ....]
var currentBtn: UIButton!
var currentImg: UIImageView!
@IBAction func onBtnClick(sender: UIButton) {
currentBtn?.setTitleColor(UIColor.blackColor(), forState:UIControlState.Normal)
sender.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)
currentBtn = sender
let index = sender.tag - 1 // one based tages
currentImg?.hidden = true
currentImg = images[index]
currentImg.hidden = false
}