swift - iOS button title color won't change -
i'm creating uibutton dynamically following code creates per specified style.
let frame = cgrect(x: 10, y: 6, width: 60, height: 30 ) let button = uibutton(frame: frame) button.settitlecolor(uicolor.blackcolor(), forstate: uicontrolstate.normal) button.backgroundcolor = uicolor.whitecolor() button.addtarget(self, action: "filterbycategory:", forcontrolevents: uicontrolevents.touchupinside) self.categoryscrollview.addsubview(button)
with button, want toggle style when tapped. following code changes background color not title color. idea why title color won't change?
func filterbycategory(sender:uibutton) { if sender.backgroundcolor != uicolor.blackcolor() { sender.settitlecolor(uicolor.whitecolor(), forstate: uicontrolstate.selected) sender.backgroundcolor = uicolor.blackcolor() } else { sender.settitlecolor(uicolor.blackcolor(), forstate: uicontrolstate.normal) sender.backgroundcolor = uicolor.whitecolor() } }
because button turn uicontrolstate.normal
after touch it, become .highlighted
, .normal
you should set sender.settitlecolor(uicolor.whitecolor(), forstate: uicontrolstate.selected)
to
sender.settitlecolor(uicolor.whitecolor(), forstate: uicontrolstate. normal)
or, set states since u did check color
sender.settitlecolor(uicolor.whitecolor(), forstate: [.normal,.selected,.highlighted])
*edit: above doesn't work, can use nsattributedstring
instead
if self.loginbutton.backgroundcolor == uicolor.blackcolor() { let tittle = nsattributedstring(string: "login", attributes: [nsforegroundcolorattributename: uicolor.blackcolor()]) loginbutton.setattributedtitle(tittle, forstate: .normal) loginbutton.backgroundcolor = uicolor.whitecolor() } else { let tittle = nsattributedstring(string: "login", attributes: [nsforegroundcolorattributename: uicolor.whitecolor()]) loginbutton.setattributedtitle(tittle, forstate: .normal) loginbutton.backgroundcolor = uicolor.blackcolor() }
Comments
Post a Comment