Thursday, May 30, 2013

UIButton backgroundImageForState example in Objective C (iOS).

UIButton backgroundImageForState

Returns the background image used for a button state.

- (UIImage *)backgroundImageForState:(UIControlState)state

Parameters
state
The state that uses the background image. Possible values are described in UIControlState.

Return Value of [UIButton backgroundImageForState]
The background image used for the specified state.

UIButton backgroundImageForState example.
NSData *data1=UIImagePNGRepresentation([twitterButton backgroundImageForState:UIControlStateNormal]);
NSData *data2=UIImagePNGRepresentation(anotherUIImage);

if([data1 isEqualToData:data2]){

}

Example of [UIButton backgroundImageForState].
for (UIView * subview in self.view.subviews) {
        if ([subview isKindOfClass:[UIImageView class]] && subview.tag == 10) {
            UIImageView* textFieldImageBackground = (UIImageView*)subview;
            textFieldImageBackground.image = [textFieldImageBackground.image stretchableImageWithLeftCapWidth:7 topCapHeight:5];
        } else if([subview isKindOfClass:[UIButton  class]] && subview.tag == 11) {
            UIButton * button = (UIButton*)subview;
            [button setBackgroundImage:[[button backgroundImageForState:UIControlStateNormal] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 4, 3)] forState:UIControlStateNormal];
        }
    }

UIButton backgroundImageForState example.
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
if (!CGRectContainsPoint([self bounds], point))
return nil;
else
{
UIImage *displayedImage = [self imageForState:[self state]];
if (displayedImage == nil) // No image found, try for background image
displayedImage = [self backgroundImageForState:[self state]];
if (displayedImage == nil) // No image could be found, fall back to
return self;
BOOL isTransparent = [displayedImage isPointTransparent:point];
if (isTransparent)
return nil;

}

End of UIButton backgroundImageForState example article.