Subclass UIButton and detect UIControlEventTouchUpInside - ios

i'm trying to detect when a button was pressed, so respond to the UIControlEventTouchUpInside event, i have tried this:
- (void)setHighlighted:(BOOL)highlighted
{
if (highlighted)
{
self.titleLabel.textColor = [UIColor whiteColor];
[self.circleLayer setFillColor:self.color.CGColor];
}
else
{
[self.circleLayer setFillColor:[UIColor clearColor].CGColor];
self.titleLabel.textColor = self.color;
}
}
but it's only when there is the finger on the button and not released, how i can detect in the subclass the touchup inside action?

What you could do is add a target in your init method, and have a boolean to keep the button state :
in CustomButton.h
#property(nonatomic,assign) BOOL selected;
in CustomButton.m
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.selected = NO;
[self addTarget:self action:#selector(toggle:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (IBAction)toggle:(id)sender{
self.selected = !self.selected;
if (self.selected)
{
self.titleLabel.textColor = [UIColor whiteColor];
[self.circleLayer setFillColor:self.color.CGColor];
}
else
{
[self.circleLayer setFillColor:[UIColor clearColor].CGColor];
self.titleLabel.textColor = self.color;
}
}

Use UIControlEventTouchDown instead of UIControlEventTouchUpInside so it's action method will call when your button will be down.

Related

UISwitch suddenly changed background color from clearColor to whiteColor

So I have a UISwitch that backgroundColor already set to clearColor in tableViewCell.m :
- (instancetype)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
{
self.selectionStyle = UITableViewCellSelectionStyleNone;
self.backgroundColor = [UIColor colorWithHexString:#"#333333"];
[self initUI];
}
return self;
}
- (void)initUI {
[self addSubview:self.topLine];
[self addSubview:self.imgView];
[self addSubview:self.titleLab];
[self addSubview:self.rightView];
[self addSubview:self.rightSwitch];
[self addSubview:self.cellLine];
[self addSubview:self.bottomLine];
}
- (UISwitch *)rightSwitch {
if (!_rightSwitch) {
self.rightSwitch = [[UISwitch alloc] init];
self.rightSwitch.frame = CGRectMake(253*kScaleXAndWidth, 8*kScaleYAndHeight, 51*kScaleXAndWidth, 31*kScaleYAndHeight);
self.rightSwitch.hidden = YES;
[self.rightSwitch setBackgroundColor:[UIColor clearColor]];
[self.rightSwitch addTarget:self action:#selector(rightSwitchClick:) forControlEvents:UIControlEventTouchUpInside];
}
return _rightSwitch;
}
rightSwitchClick is a block, then in cellForRowAtIndexPath TableViewController.m :
QuickLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:QuickLoginCellID forIndexPath:indexPath];
cell.rightView.hidden = YES;
cell.rightSwitch.hidden = NO;
__block QuickLoginCell *blockCell = cell;
if (isIDlogin) {
[cell.rightSwitch setEnabled:NO];
}
else{
[cell.rightSwitch setEnabled:YES];
}
cell.rightSwitch.on = NO;
cell.bottomLine.hidden = NO;
if (![BetwayUtils isEmptyString:patternLock]) {
cell.rightSwitch.on = YES;
cell.bottomLine.hidden = YES;
}
[cell.imgView setImage:[UIImage imageNamed:#"ic_patternLock"]];
cell.rightSwitchAddClick = ^{
if (blockCell.rightSwitch.on) {
PatternLockViewController *vc = [PatternLockViewController new];
[strongSelf.navigationController pushViewController:vc animated:YES];
}
else{
}
};
so when turn on it will directly go to PatternLockViewController, and after I have set the patternLock it will pop to TableViewController again and the switch will be turned on now. the problem is when I try to switch it off the backgroundColor suddenly change to white like this :
When I remove :
PatternLockViewController *vc = [PatternLockViewController new];
[strongSelf.navigationController pushViewController:vc animated:YES];
so inside the block there is no code and the UISwitch backgroundColor is clearColor, I tried to switch on and off and it works as it supposed to be. so i am a little bit confused on this matter since I dont set UISwitch backgroundColor to white anywhere.
UPDATE
Already tried using delegate to refresh table when pop from patternlockviewcontroller but still no avail
I solve it using :
- (void)prepareForReuse {
[super prepareForReuse];
[self.rightSwitch setBackgroundColor:[UIColor clearColor]];
[self.rightSwitch setTintColor:[UIColor whiteColor]];
[self.rightSwitch setThumbTintColor:[UIColor whiteColor]];
}
on my tableViewCell.m I hope it will help someone here.

Change button's background colour

I am working on a project in which I create a subclass for UIButton for setting the gradient background colour.Its working fine but now there are two tabs in a ViewController there is two buttons suppose A and B. I want to change colour of button A when I clicked on Button B same like tabs functionality:
Sub class of UIButton:
// .h_file
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface grediantButton : UIButton
#property(nonatomic)IBInspectable UIColor*topColor;
#property(nonatomic)IBInspectable UIColor*bottomColor;
#property(nonatomic)IBInspectable CGFloat cornerRadius;
- (void)customInit;
#end
// .m file
#import "grediantButton.h"
#import "UIColor+myColor.h"
#implementation grediantButton
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.topColor = [UIColor clearColor];
self.bottomColor = [UIColor clearColor];
self.cornerRadius = 1;
[self customInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self customInit];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[self customInit];
}
- (void)setNeedsLayout {
[super setNeedsLayout];
[self setNeedsDisplay];
}
- (void)prepareForInterfaceBuilder {
[self customInit];
}
- (void)customInit {
self.layer.cornerRadius = self.cornerRadius;
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
gradientLayer.cornerRadius = self.cornerRadius;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[self.topColor CGColor], (id)[self.bottomColor CGColor],nil];
[self.layer setMasksToBounds:YES];
[self.layer insertSublayer:gradientLayer atIndex:0];
}
My VC Code:
#pragma mark:AddnewTownshipVC
- (IBAction)addnewTownShip:(id)sender {
[self.addnewTwnBtn setTopColor:[UIColor getTabTopColor]];
[self.addnewTwnBtn setBottomColor:[UIColor getTabBotColor]];
[self.viewalltownBtn setTopColor:[UIColor blackColor]];
[self.viewalltownBtn setBottomColor:[UIColor blackColor]];
}
#pragma mark:viewalltownshipVC
- (IBAction)viewAllTownship:(id)sender {
[self.addnewTwnBtn setTopColor:[UIColor blackColor]];
[self.addnewTwnBtn setBottomColor:[UIColor blackColor]];
[self.viewalltownBtn setTopColor:[UIColor getTabTopColor]];
[self.viewalltownBtn setBottomColor:[UIColor getTabBotColor]];
}
Tabs is like:
what happen when I click on black one tab
You should set state for UIButton multiple states.
For example, set different background images for different states.
[button setBackgroundImage:naomalImage forState:UIControlStateNormal];
[button setBackgroundImage:selectedImage forState:UIControlStateSelected];
And then, just control states.
- (IBAction)addnewTownShip:(id)sender {
button.selected = YES;
}
...
Thank you all for response.
I solved my issue by change some code in my - (void)customInit method
- (void)customInit {
self.layer.cornerRadius = self.cornerRadius;
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
gradientLayer.cornerRadius = self.cornerRadius;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[self.topColor CGColor], (id)[self.bottomColor CGColor],nil];
[self.layer setMasksToBounds:YES];
if([[self.layer sublayers] objectAtIndex:0]){
[self.layer replaceSublayer:[[self.layer sublayers] objectAtIndex:0] with:gradientLayer];
}else{
[self.layer insertSublayer:gradientLayer atIndex:0];
}
}
and call this method in
#pragma mark:AddnewTownshipVC
- (IBAction)addnewTownShip:(grediantButton*)sender {
[sender setTopColor:[UIColor getTabTopColor]];
[sender setBottomColor:[UIColor getTabBotColor]];
[sender customInit];
[self.viewalltownBtn setTopColor:[UIColor blackColor]];
[self.viewalltownBtn setBottomColor:[UIColor blackColor]];
[self.viewalltownBtn customInit];
// sender.isSelected = true;
// self.viewalltownBtn.isSelected = false;
}
#pragma mark:viewalltownshipVC
- (IBAction)viewAllTownship:(grediantButton*)sender {
[self.addnewTwnBtn setTopColor:[UIColor blackColor]];
[self.addnewTwnBtn setBottomColor:[UIColor blackColor]];
[self.addnewTwnBtn customInit];
[sender setTopColor:[UIColor getTabTopColor]];
[sender setBottomColor:[UIColor getTabBotColor]];
[sender customInit];
}
simply go to the attribute inspector in storyboard see in bottom in it there has background colour you can change with it.
see here :-
https://i.stack.imgur.com/A6ecY.png

cornerRadius causes long load time in iOS 10

I have a problem with my App. I have a View with 25 Buttons with changed cornerRadius. Since iOS 10 it takes about 5-6 seconds till this View loads.
Here is the relevant code:
- (void)setupTiles {
for (TileButton *btn in tiles_btn) {
btn.alpha = 0.0;
btn.layer.borderColor = [UIColor blackColor].CGColor;
btn.layer.borderWidth = 1.0f;
[btn layoutIfNeeded];
bin.layer.cornerRadius = btn.frame.size.width*0.3;
}
[self colorTilesWithArray:currentTileColors];
}
When i remove the following lines, is loads the view instantly:
[btn layoutIfNeeded];
bin.layer.cornerRadius = btn.frame.size.width*0.3;
The Buttons are grouped in an outlet collection, in case that's necessary to know.
Does anybody have a solution?
Thanks in advance!
Nico
Image 1: This takes about 5-6 seconds
Image 2: This is the View that will be loaded
TileButton.h-File:
#interface TileButton : UIButton
#property (nonatomic) int colorMode;
+ (UIColor *)blue;
+ (UIColor *)red;
+ (UIColor *)green;
+ (UIColor *)yellow;
+(UIColor *)colorForColorCode:(int)colorCode;
-(int)colorMode;
#end
TileButton.m-File:
#implementation TileButton
- (instancetype)init {
self = [super init];
if (self) {
self.layer.cornerRadius = self.frame.size.width*0.3;
}
return self;
}
+(UIColor *)blue {
return [UIColor colorWithRed:41.0/255.0 green:161.0/255.0 blue:255.0/255.0 alpha:1];
}
+(UIColor *)red {
return [UIColor colorWithRed:255.0/255.0 green:71.0/255.0 blue:109.0/255.0 alpha:1];
}
+(UIColor *)green {
return [UIColor colorWithRed:0.0/255.0 green:185.0/255.0 blue:30.0/255.0 alpha:1];
}
+(UIColor *)yellow {
return [UIColor colorWithRed:255.0/255.0 green:198.0/255.0 blue:26.0/255.0 alpha:1];
}
+(UIColor *)colorForColorCode:(int)colorCode {
switch (colorCode) {
case 1:
return [TileButton blue];
break;
case 2:
return [TileButton red];
break;
case 3:
return [TileButton green];
break;
case 4:
return [TileButton yellow];
break;
default:
return [UIColor blackColor];
break;
}
}
-(int)colorMode {
if (CGColorEqualToColor(self.backgroundColor.CGColor, [TileButton blue].CGColor))
return 1;
else if (CGColorEqualToColor(self.backgroundColor.CGColor, [TileButton red].CGColor))
return 2;
else if (CGColorEqualToColor(self.backgroundColor.CGColor, [TileButton green].CGColor))
return 3;
else if (CGColorEqualToColor(self.backgroundColor.CGColor, [TileButton yellow].CGColor))
return 4;
else
return -1;
}
#end
Since you are creating the buttons in Interface Builder you will need to set the cornerRadius in the awakeFromNib method. It should look something like this:
#implementation TileButton
-(void) awakeFromNib {
[super awakeFromNib];
self.layer.cornerRadius = self.frame.size.width*0.3;
}
https://developer.apple.com/reference/objectivec/nsobject/1402907-awakefromnib
Why can't you set the corner radius outside the for loop?
UIButton *btn = [UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; // set your frame here
bin.layer.cornerRadius = btn.frame.size.width*0.3; // width stays the same, set it here
for (TileButton *btn in tiles_btn) {
btn.alpha = 0.0;
btn.layer.borderColor = [UIColor blackColor].CGColor;
btn.layer.borderWidth = 1.0f;
// you need to set the button frame here
btn.frame = CGRectMake(0,0,0,0);
[btn layoutIfNeeded];
}
[self colorTilesWithArray:currentTileColors];
Assuming that TileButton is a subclass of UIButton, on initialization, you can set the TileButton to have your custom color, width, and corner radius. That way all of your buttons already have the specified customization on button creation.

Objective-C highlight UIButton when selected / unselected

I have a UIButton inside a UIView, when the UIButton is selected I would like have a background colour of dark gray...is this possible?
UIView *toolbar = [[UIView alloc]initWithFrame:CGRectMake(10, 50, 40, 160)];
[toolbar setBackgroundColor:[UIColor colorWithWhite: 0.70 alpha:0.5]];
toolbar.layer.cornerRadius = 5;
UIButton *penTool = [UIButton buttonWithType:UIButtonTypeCustom];
penTool.frame = CGRectMake(5, 0, 30, 30);
[penTool setImage:[UIImage imageNamed:#"pen-but" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
[penTool addTarget:self action:#selector(drawButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
penTool.autoresizingMask = UIViewAutoresizingNone;
penTool.exclusiveTouch = YES;
penTool.tag = 1;
[toolbar addSubview:penTool];
What if you can do this?
[button setBackgroundColor:[UIColor greenColor]
forState:UIControlStateSelected];
Let's give a great API for every state, not just selected, just like UIButton default API's ability to change image and title for every state.
BGButton.h
#import <UIKit/UIKit.h>
#interface BGButton : UIButton
- (void)setBackgroundColor:(UIColor *)backgroundColor
forState:(UIControlState)state;
#end
BGButton.m
#import "BGButton.h"
#implementation BGButton {
NSMutableDictionary *_stateBackgroundColor;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_stateBackgroundColor = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
[super setBackgroundColor:backgroundColor];
/*
* If user set button.backgroundColor we will set it to
* normal state's backgroundColor.
* Check if state is on normal state to prevent background being
* changed for incorrect state when updateBackgroundColor method is called.
*/
if (self.state == UIControlStateNormal) {
[self setBackgroundColor:backgroundColor forState:UIControlStateNormal];
}
}
- (void)setBackgroundColor:(UIColor *)backgroundColor
forState:(UIControlState)state {
NSNumber *key = [NSNumber numberWithInt:state];
[_stateBackgroundColor setObject:backgroundColor forKey:key];
}
/*
* state is synthesized from other flags. So we can't use KVO
* to listen for state changes.
*/
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
[self stateDidChange];
}
- (void)setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
[self stateDidChange];
}
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
[self stateDidChange];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[self stateDidChange];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self stateDidChange];
}
- (void)stateDidChange {
[self updateBackgroundColor];
}
- (void)updateBackgroundColor {
NSNumber *key = [NSNumber numberWithInt:self.state];
self.backgroundColor = [_stateBackgroundColor objectForKey:key];
}
#end
You can use it like the default UIButton API
BGButton *button = [[BGButton alloc] init];
[button setBackgroundColor:[UIColor greenColor]
forState:UIControlStateSelected];
[button setBackgroundColor:[UIColor blueColor]
forState:UIControlStateHighlighted];
[button setBackgroundColor:[UIColor orangeColor]
forState:UIControlStateDisabled];
Even if you use
button.backgroundColor = [UIColor redColor];
You will stay safe, it will be translated into
[button setBackgroundColor:[UIColor redColor]
forState:UIControlStateNormal];
if you have this code
[self.view addSubview:toolbar];
then just implement your button selector
-(void)drawButtonTapped:(UIButton*)button{
if (button.selected) {
button.backgroundColor = [UIColor clearColor];
button.selected = NO;
}else{
button.backgroundColor = [UIColor darkGrayColor];
button.selected = YES;
}
}
I don't know why guys would go through such trouble when we have this functionality built-in inside UIButton. All you need to do is use UIButtonTypeSystem That's all.
[UIButton buttonWithType:UIButtonTypeSystem]
Seriously, there's nothing more to it. Have a look at it's behavior in the screenshots.
INTERFACE BUILDER
RUN TIME
Want to change color, set tintColor to color of your choice.
ADVANTAGES
Covers titles with dynamic lengths. Not applied on all button width.
When selected, title color is transparent, your background can be seen through, try to use an image as a background.
Let's hope you have at least iOS7 as deployment target. UIButtonTypeSystem was introduce with revised UI design guidelines of iOS7 and has been there for almost 3 years.
Good Luck!
I used a UIButton subclass here:
#import "CustomButton.h"
#interface CustomButton()
#property (nonatomic,strong) UIColor *originalColor;
#end
#implementation CustomButton
- (void)didMoveToSuperview
{
self.originalColor = self.superview.backgroundColor;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.superview.backgroundColor = [UIColor grayColor];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
if ([self hitTest:location withEvent:nil]) {
self.superview.backgroundColor = [UIColor grayColor];
self.originalColor = self.superview.backgroundColor;
}
else
{
self.superview.backgroundColor = self.originalColor;
}
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.superview.backgroundColor = self.originalColor;
}
#end
If you subclass your button from this class, It should give you the desired effect. This also gives you the highlight effect. If you wish you can disable it by removing the line on touchesBegan.
Just try to Override the UIButton with the following Method...
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = [UIColor darkGray];
}
}
I think you'll be want to change the selectedImage for flexibility not the background.
Add another image (e.g. pen-but-selected) in the project. Add this 2nd line for setImage:
[penTool setImage:[UIImage imageNamed:#"pen-but-selected" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateSelected];
- (void)drawButtonTapped:(UIButton *)button {
button.selected = !button.selected;
}
If you still want to change background color. #jamil's answer would work. Make sure the buttonImage has transparent part so you can see the buttonBackground through the buttonImage.
Try using a boolean, or some other reference to the selection state of the button. You could also make use of a 'highlightColour' as well as the 'selectedColour' if you wanted closer control (should probably do this for better UX).
bool buttonIsSelected = false;
UIColor * selectedColour = [UIColor redColor];
UIColor * defaultColour = [UIColor blueColor];
UIButton * button = [UIButton new];
button.frame = CGRectMake(0,0,100,100);
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
[button addTarget:self action:#selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:#selector(buttonTouchCancel:) forControlEvents:UIControlEventTouchCancel];
[button addTarget:self action:#selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
-(void)buttonTouchUp:(UIButton *)button {
if (buttonIsSelected){
buttonIsSelected = false;
button.backgroundColor = defaultColour;
} else {
buttonIsSelected = true;
button.backgroundColor = selectedColour;
}
}
-(void)buttonTouchCancel:(UIButton *)button {
button.backgroundColor = defaultColour;
if (buttonIsSelected){
button.backgroundColor = selectedColour;
}
}
-(void)buttonTouchDown:(UIButton *)button {
button.backgroundColor = selectedColour;
}
-(void)OnSelect:(UIButton*)button{
if (button.selected) {
button.backgroundColor = [UIColor blue];
button.selected = NO;
}else{
button.backgroundColor = [UIColor darkGrayColor];
button.selected = YES;
}
}
use the above this will work..
-(void)buttonTapped:(UIButton*)button{
button.selected =! button.selected;
if (button.selected)
button.backgroundColor = [UIColor grayColor];
else
button.backgroundColor = [UIColor clearColor];
}

Set Selected State of CAGradient UIButton in iOS

Hi I have made a custom button in code using corner radius CAGradientLayer and border colour in one of my view controllers like the below:
phoneButton = [CustomButton buttonWithType:UIButtonTypeCustom];
phoneButton.frame = CGRectMake(6, 363, 99, 48);
phoneButton.titleLabel.font = [UIFont fontWithName:#"Futura-Medium" size:14];
phoneButton.titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:1.0];
phoneButton.titleLabel.shadowOffset = CGSizeMake(0, 1);
[phoneButton setTitle:#"Phone" forState:UIControlStateNormal];
[phoneButton addTarget:self action:#selector(phone) forControlEvents:UIControlEventTouchUpInside];
gradient = [CAGradientLayer layer];
gradient.frame = phoneButton.bounds;
gradient.cornerRadius = 8;
gradient.borderColor = [[UIColor whiteColor]CGColor];
gradient.borderWidth = 2.0;
gradient.colors = [NSArray arrayWithObjects:(id)[[sharedManager cellGradientEnd] CGColor], (id)[[sharedManager cellGradientStart] CGColor], nil];
[phoneButton.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:phoneButton];
Now I would like to set the selected/highlighted color of the button on selection. How do I do this. I read make a UIbutton subclass and override setSelected but I dont have a clue how to do it. Here is customButton subclass.m
#import "CustomButton.h"
#implementation CustomButton
#synthesize sharedManager;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
sharedManager = [[MySingleton alloc]init];
}
return self;
}
-(void) setHighlighted:(BOOL)highlighted {
if(highlighted) {
NSLog(#"Highlighted");
} else {
NSLog(#"Not Highlighted");
}
[super setHighlighted:highlighted];
}
-(void) setSelected:(BOOL)selected {
if(selected) {
NSLog(#"Selected");
} else {
NSLog(#"Not Selected");
}
[super setSelected:selected];
}
#end
Or just dim the button on selection would be good? I should add that the button is not in a Xib.
I figured it out just by creating a selected Gradient and unselected Gradient state of the button in subclass.m now it is all working great!
- (CustomButton *)buttonWithType:(UIButtonType)type
{
return [self buttonWithType:UIButtonTypeCustom];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (id)initWithCoder:(NSCoder *)coder
{
//Call the parent implementation of initWithCoder
self = [super initWithCoder:coder];
//Custom drawing methods
if (self)
{
[self drawBackgroundLayer];
[self drawHighlightBackgroundLayer];
highlightBackgroundLayer.hidden = YES;
}
return self;
}
-(void)loadSingleton{
sharedManager = [[MySingleton alloc]init];
}
- (void)layoutSubviews
{
// Set gradient frame (fill the whole button))
backgroundLayer.frame = self.bounds;
// Set inverted gradient frame
highlightBackgroundLayer.frame = self.bounds;
[super layoutSubviews];
}
- (void)drawBackgroundLayer
{
[self loadSingleton];
// Check if the property has been set already
if (!backgroundLayer)
{
backgroundLayer = [CAGradientLayer layer];
backgroundLayer.cornerRadius = 8;
backgroundLayer.borderWidth = 1.5;
backgroundLayer.borderColor = [UIColor whiteColor].CGColor;
backgroundLayer.colors = [NSArray arrayWithObjects:(id)[[sharedManager cellGradientEnd] CGColor], (id)[[sharedManager cellGradientStart] CGColor], nil];
// Add the gradient to the layer hierarchy
[self.layer insertSublayer:backgroundLayer atIndex:0];
}
}
- (void)drawHighlightBackgroundLayer
{
[self loadSingleton];
if (!highlightBackgroundLayer)
{
highlightBackgroundLayer = [CAGradientLayer layer];
highlightBackgroundLayer.cornerRadius = 8;
highlightBackgroundLayer.borderWidth = 1.5;
highlightBackgroundLayer.borderColor = [UIColor whiteColor].CGColor;
highlightBackgroundLayer.colors = [NSArray arrayWithObjects:(id)[[sharedManager cellSelectedGradientEnd] CGColor], (id)[[sharedManager cellSelectedGradientStart] CGColor], nil];
[self.layer insertSublayer:highlightBackgroundLayer atIndex:1];
}
}
and setting the selected state on or off
- (void)setHighlighted:(BOOL)highlighted
{
NSLog(#"Selected");
// Disable implicit animation
[CATransaction begin];
[CATransaction setDisableActions:YES];
// Hide/show inverted gradient
highlightBackgroundLayer.hidden = !highlighted;
[CATransaction commit];
[super setHighlighted:highlighted];
}
Have you tried invoking super and then invoking setNeedsDisplay on self?
It should cause your display functionality to be invoked at the appropriate time, and in that code you should be checking for selected/highlighted.
If I understand correctly what you are trying to do, I would suggest the following approach:
move the CAGradientLayer inside of your CustomButton implementation (so it would become a CustomGradientButton);
when you want to set the selected state for the custom button, change the CAGradientLayer gradientColors by changing their saturation and brightness.
By doing this, your button will change its appearance in the selected state.
A way to modify saturation and brightness could be through this UIColor category of mine:
#interface UIColor (LighterDarkerColor)
- (UIColor*)colorWithSaturation:(float)saturationFactor
brightness:(float)brightnessFactor;
#end
#implementation UIColor (LighterDarkerColor)
- (UIColor*)colorWithSaturation:(float)saturationFactor
brightness:(float)brightnessFactor {
float hue = 0.0;
float saturation = 0.0;
float brightness = 0.0;
float alpha = 0.0;
if ([self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha])
return [UIColor colorWithHue:hue saturation:saturation*saturationFactor
brightness:brightness*brightnessFactor alpha:alpha];
return self;
}
#end
You could do, e.g.:
UIColor* selectedColorStart = [[sharedManager cellGradientStart] colorWithSaturation:0.65 brightness:1.2];
to get a less saturated, brighter version of your cellGradientStart color. Then in your setSelected method you would modify your CAGradientLayer:
gradient.colors = [NSArray arrayWithObjects:(id)[selectedColorEnd CGColor], (id)[selectedColorStart CGColor], nil];
This approach works for me, although you need to fine-tune your selection of saturation and brightness working for your case.

Resources