Programmatically Disable Highlight on Click of UIB

2020-07-06 09:26发布

问题:

There must be a way to do this, but I can't find it. I have a button I have created programmatically:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(25, self.view.frame.size.height/4, 200, 350);
[button setTitle:@"Inbox" forState:UIControlStateNormal];
[button addTarget:self action:@selector(popViewController:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

All I want is for the button not to highlight or change in appearance in any way when it is touched. So far I have tried the following when creating the button:

[button setBackgroundImage:[UIImage imageNamed:nil] forState:UIControlStateSelected | UIControlStateHighlighted];

AND

[button setBackgroundImage:nil forState:UIControlStateSelected];

AND

[button setAdjustsImageWhenHighlighted:NO];

AND

button.showsTouchWhenHighlighted = NO;

Then in the button action I tried:

[sender setHighlighted:!sender.isHighlighted];

AND

[sender setSelected:!sender.isSelected];

None of these work.

回答1:

Make your UIButton a custom button and then apply a UIImage background to it. It won't highlight or change when pressed

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];


回答2:

You can just simply set adjustImageWhenHighlighted to No.

button.adjustsImageWhenHighlighted = NO;


回答3:

Bro, I've tried different ways as you. But finally have found my own recipe:

I don't know how it works with a custom button with UIImage on it but for a simple UIButton with the text for a heighlighted state You should simply set the same settings as you have in the default state.

And for highlighted state for image property in IB set a whitespace. You may found that sometimes button might have a strange little offset when you click on it. For that case, remove the text from textField for highlighted state. It will resolve this issue.

Then on your click event you will see no blinks at all.



回答4:

For those using a custom PNG image with tint colour switched on, you can avoid the dimming (e.g. from white to grey) with this code:

 clearButton.tintAdjustmentMode = UIViewTintAdjustmentModeNormal;