I am using custom UIButton
s, and what I want to do is make it so that when a user touches the button it dims, or turns a grayish color, like the regular button does.
I just want the text to temporarily change color temporally when the users lifts there figure it will be back to the regular color.
I have tried this code:
button.showsTouchWhenHighlighted = TRUE;
but that just makes a white circle around it which is not what I'm looking for.
Thanks for the help.
The easiest way I've come across is:
[myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];
You can utilize the following UIControlEvents
:
UIControlEventTouchDown
UIControlEventTouchUpInside
UIControlEventTouchUpOutside
Assign target-action methods to them appropriately like so:
//when touch initiated
[myButton addTarget:self
action:@selector(buttonTouchStartAct:)
forControlEvents:UIControlEventTouchDown];
//on touch released outside button bounds
[myButton addTarget:self
action:@selector(buttonTouchEndAct:)
forControlEvents:UIControlEventTouchUpOutside];
//on touch released while still inside button bounds (most commonly used)
[myButton addTarget:self
action:@selector(buttonAct:)
forControlEvents:UIControlEventTouchUpInside];
-(void)buttonTouchStartAct:(UIButton *)sender
{
[sender.titleLabel setTextColor:[UIColor redColor]];
}
-(void)buttonTouchEndAct:(UIButton *)sender
{
[sender.titleLabel setTextColor:[UIColor greenColor]];
}
-(void)buttonAct:(UIButton *)sender
{
//touch ended in this case too
[self buttonTouchEndAct:sender];
//...
//your main button logic
//...
}
//when touch initiated
[myButton addTarget:self
action:@selector(buttonTouchStartAct:)
forControlEvents:UIControlEventTouchDown];
//on touch released outside button bounds
[myButton addTarget:self
action:@selector(buttonTouchEndAct:)
forControlEvents:UIControlEventTouchUpOutside];
//on touch released while still inside button bounds (most commonly used)
[myButton addTarget:self
action:@selector(buttonAct:)
forControlEvents:UIControlEventTouchUpInside];
and then inside the method change the color of the button
Try changing alpha of title label on button click like this
- (IBAction)buttonClick:(id)sender {
UIButton *button = sender;
[UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveEaseInOut animations:^
{
[button.titleLabel setAlpha:0.5];
} completion:^(BOOL finished)
{
[button.titleLabel setAlpha:1];
}];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.