Change button text color when clicked on IOS

I know this question is asked a lot and many of the answers are correct, I have some code where I ran into the problem. I have radio buttons on which the background color of the button and the color of the text change when the button is clicked. The background color changes as I expected, but the text color turns blue when the button is clicked. I have coded it to change white on click, but when I click the button it changes the text area to blue, I am confused about making mistakes. My code:

 self.selectedTitleColor = [UIColor whiteColor];
self.selectedBackgroundColor = [UIColor redColor];

self.unselectedTitleColor = [UIColor blackColor];
self.unselectedBackgroundColor = [UIColor whiteColor];

- (IBAction)House:(id)sender {

[sender setSelected: ![sender isSelected]];
[self.flat setSelected:NO];
[self.lowerP setSelected:NO];
[self.upperP setSelected:NO];
[self.farmH setSelected:NO];
[self.pentH setSelected:NO];
[self.roomB setSelected:NO];


[self updateButtonColors];

      

}

-(void)updateButtonColors {
if (self.house.selected) {
    [self.house setTitleColor:self.selectedTitleColor forState:UIControlStateNormal];
    [self.house setBackgroundColor:self.selectedBackgroundColor];

    House=_house.titleLabel.text;
    ImageViewD = [NSString stringWithFormat:@"%@",House];

    NSLog(@"HHHH  %@",ImageViewD);

} else {
    [self.house setTitleColor:self.unselectedTitleColor forState:UIControlStateNormal];
    [self.house setBackgroundColor:self.unselectedBackgroundColor];
        }

      

}

enter image description here

+3


source to share


2 answers


Change the button type in the storyboard from system to custom .



enter image description here

+2


source


Your best bet is to pass all properties to the storyboard. You can take two images for your color and set the backgroundImage to the UIButton state .

See below image for that.

[ Normal State]

Selected state

I have a bind button with the method below and its code:



- (IBAction)clicked:(id)sender {
    UIButton *btn = (UIButton *)sender;
    btn.selected = !btn.selected;
}

      

Below are the images I took for reference.

Red.png

Green.png

Hope this helps you.

0


source







All Articles