Thursday, May 30, 2013

UIButton adjustsImageWhenHighlighted example in Objective C (iOS).

UIButton adjustsImageWhenHighlighted

A Boolean value that determines whether the image changes when the button is highlighted.

@property(nonatomic) BOOL adjustsImageWhenHighlighted

Discussion of [UIButton adjustsImageWhenHighlighted]
If YES, the image is drawn lighter when the button is highlighted. The default value is YES.

UIButton adjustsImageWhenHighlighted example.
UIButton *imageBtn = [UIButton ...
imageBtn.adjustsImageWhenHighlighted = NO;

[imageBtn addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];

[imageBtn addTarget:self action:@selector(doHighlighted:) forControlEvents:UIControlEventTouchDown];
[imageBtn addTarget:self action:@selector(doHighlighted:) forControlEvents:UIControlEventTouchDragEnter];
    [imageBtn addTarget:self action:@selector(doCancelHighlighted:) forControlEvents:UIControlEventTouchDragExit];

Example of [UIButton adjustsImageWhenHighlighted].
[self setImage:image forState:UIControlStateNormal];
[self setAdjustsImageWhenHighlighted:NO];

UIButton adjustsImageWhenHighlighted example.
-(void) addRightButtonWithImage:(UIImage*)buttonImage highlightImage:(UIImage*)highlightImage
{
    rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.adjustsImageWhenHighlighted = NO;
    rightButton.showsTouchWhenHighlighted = NO;
    [[rightButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
    [rightButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [rightButton setBackgroundImage:highlightImage forState:UIControlStateHighlighted | UIControlStateSelected];
    [rightButton setBackgroundImage:highlightImage forState:UIControlStateSelected];
    rightButton.frame = CGRectMake(160.0, 367, 160.0, 49.0);
    [rightButton addTarget:self action:@selector(rightTabPressed) forControlEvents:UIControlEventTouchUpInside];

    UILongPressGestureRecognizer *longGesture = [[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGestureDetected:)]autorelease];
    longGesture.delaysTouchesBegan = YES;
    [rightButton addGestureRecognizer:longGesture];

    [self.view addSubview:rightButton];
}

End of UIButton adjustsImageWhenHighlighted example article.