Reputation: 6323
I am subclassing UIButton. But I need to know the state that the button is in to draw the color of button for up or down:
- (void)drawRect:(CGRect)rect{
if (state==UIControlStateNormal) {
//draw rect RED
}
if (state==UIControlEventTouchDown)
//draw rect BLUE
}
}
Upvotes: 3
Views: 3002
Reputation: 6323
To redraw rect, I did this...
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
myState = 1;
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
myState = 0;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
NSLog(@"drawRect state: %d", self.state);
NSLog(@"rect %@", NSStringFromCGRect(self.frame));
c = UIGraphicsGetCurrentContext();
if (myState==0){
///////// plot border /////////////
CGContextBeginPath(c);
CGContextSetLineWidth(c, 2.0);
CGContextMoveToPoint(c, 1, 1);
CGContextAddLineToPoint(c, 1, 20);
CGContextAddLineToPoint(c, 299, 20);
CGContextAddLineToPoint(c, 299, 1);
CGContextSetRGBFillColor(c, 0.0, 0.0, 1.0, 1.0);
CGContextFillPath(c);
CGContextClosePath(c);
CGContextStrokePath(c);
}else{
CGContextBeginPath(c);
CGContextSetLineWidth(c, 2.0);
CGContextMoveToPoint(c, 1, 20);
CGContextAddLineToPoint(c, 1, 40);
CGContextAddLineToPoint(c, 299, 40);
CGContextAddLineToPoint(c, 299, 20);
CGContextSetRGBFillColor(c, 1.0, 0.0, 1.0, 1.0);
CGContextFillPath(c);
CGContextClosePath(c);
CGContextStrokePath(c);
}
}
Upvotes: 0
Reputation: 38728
Did you even try looking at the docs?
UIButton
has a superclassUIButton
's superclassstate
propertyThe accepted answer is slightly incorrect and could lead to some annoyingly difficult bug to track down.
The header for UIControl
declares state
as
@property(nonatomic,readonly) UIControlState state; // could be more than one state (e.g. disabled|selected). synthesized from other flags.
Now looking up to see how UIControlState
is defined we see
enum {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set
UIControlStateDisabled = 1 << 1,
UIControlStateSelected = 1 << 2, // flag usable by app (see below)
UIControlStateApplication = 0x00FF0000, // additional flags available for application use
UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use
};
typedef NSUInteger UIControlState;
Therefore as you are dealing with a bit mask you should check for the state appropriately e.g.
if (self.state & UIControlStateNormal) { ... }
You could do this by drawing into an image and then setting the image as the background e.g.
- (void)clicked:(UIButton *)button;
{
UIGraphicsBeginImageContext(button.frame.size);
// Draw gradient
UIImage *gradient = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[button setBackgroundImage:image forState:UIControlStateNormal];
}
Upvotes: 5
Reputation: 4248
Since state
is a property, you can use self.state
to access it.
Update:
See the next answer's update.
Upvotes: 1