Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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];
like image 988
HurkNburkS Avatar asked Jan 15 '14 09:01

HurkNburkS


2 Answers

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 2.x version

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

EDIT: Swift 3.0 version

cancelButton.setTitleColor(.white, for: .highlighted)
like image 76
Christian A. Strømmen Avatar answered Sep 28 '22 22:09

Christian A. Strømmen


Use titleColor:forState: to set the color of text on selection/highlight/disable for the respective states.

like image 38
Praveen S Avatar answered Sep 28 '22 23:09

Praveen S