HurkNburkS HurkNburkS - 6 months ago 42
iOS Question

UIButton not showing highlight when touched

I am trying to highlight my UIButton with a custom UIColor light grey and make the text go white... however I am not sure how to do this... this is how far I have gotten with creating the UIButton any help would be appreciated.

cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cancelButton.frame = CGRectMake(10.0, calculatorView.frame.size.height-55, 100.0, 45.0);
[cancelButton addTarget:self action:@selector(calculateMethod:)forControlEvents:UIControlEventTouchDown];
[[cancelButton titleLabel] setFont:[UIFont fontWithName: @"Super-text" size:20.0]];
[cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];

Answer

To get the white text on highlight just do:

        [cancelButton setTitleColor:[UIColor whiteColor]
                       forState:UIControlStateHighlighted];

To get the background to change you need to either do setBackgroundImage:forState: and use a UIImage with the pattern color, or subclass UIButton and set the appropriate background color in the setHighlight: method.

EDIT: Swift version

        cancelButton.setTitleColor(.whiteColor(), forState: .Highlighted)
Comments