将按钮的文本颜色从黑色更改为白色,然后还原返回
问题描述:
我在滑出菜单中有十个按钮。如何通过选择将十个按钮的文本颜色从黑色更改为白色,然后在用户单击另一个按钮时恢复为原始状态。将按钮的文本颜色从黑色更改为白色,然后还原返回
我通过按键循环逐个和我使用的代码
@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
}
问题与这种状态是按钮的颜色保持白色当我选择其他按钮。我想,当用户选择另一个按钮用于选择
控制状态是几乎不存在了几秒钟,当我点击按钮来改变文字颜色为黑色
答
试试这个:
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.
}
或者您可以使用它涉及较少的循环不同的方式。
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
}
答
你可能要为特定状态的颜色,然后在需要时更改按钮状态。听起来就像你想要一个收音机类型的按钮设置,所以有一个数组中的按钮,当任何一个按钮被轻敲时,将该按钮的状态更改为“选定”,其他人“正常”或类似的东西。
这些所有按钮不会像单选按钮一样工作。在每个按钮上单击您应该还原其他按钮状态。 –
我所有的按钮命名不同。我应该在每个循环后恢复原状。谢谢 – Nick