2012-10-13 45 views
2

我已經設置了一個輕按手勢識別器並將識別器添加到了uibutton中。該按鈕有一個背景圖像。當我點擊按鈕時,它根本沒有突出顯示,我唯一能做的就是改變它的alpha值。無法通過TapGestureRecognizer使UIButton突出顯示

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)]; 
    singleTap.cancelsTouchesInView = NO; 

    [btnNext addGestureRecognizer:singleTap]; 


- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture 
{ 
UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil]; 
NSLog(@"Touch event view: %@",[tappedView class]); 
UIButton *myButton = (UIButton *) tappedView; 
[self highlightButton:myButton]; 
tappedView.alpha = 0.5f; 

} 

任何將不勝感激。謝謝

回答

2

您可以使用手勢識別器攔截觸摸事件,然後以編程方式將識別器添加到所有的uibutton中。例如:

// 
// HighlighterGestureRecognizer.h 
// Copyright 2011 PathwaySP. All rights reserved. 
// 

#import <Foundation/Foundation.h> 


@interface HighlightGestureRecognizer : UIGestureRecognizer { 
    id *beganButton; 
} 

@property(nonatomic, assign) id *beganButton; 

@end 
and the implementation: 

// 
// HighlightGestureRecognizer.m 
// Copyright 2011 PathwaySP. All rights reserved. 
// 

#import "HighlightGestureRecognizer.h" 


@implementation HighlightGestureRecognizer 

@synthesize beganButton; 

-(id) init{ 
    if (self = [super init]) 
    { 
     self.cancelsTouchesInView = NO; 
    } 
    return self; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    self.beganButton = [[[event allTouches] anyObject] view]; 
    if ([beganButton isKindOfClass: [UIButton class]]) { 
     [beganButton setBackgroundImage:[UIImage imageNamed:@"grey_screen"] forState:UIControlStateNormal]; 
     [self performSelector:@selector(resetImage) withObject:nil afterDelay:0.2]; 

    } 
} 

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
} 

- (void)reset 
{ 
} 

- (void)ignoreTouch:(UITouch *)touch forEvent:(UIEvent *)event 
{ 
} 

- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer 
{ 
    return NO; 
} 

- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer 
{ 
    return NO; 
} 

- (void)resetImage 
{ 
    [beganButton setBackgroundImage: nil forState:UIControlStateNormal]; 
} 

@end 

你的手勢識別器添加到您的按鈕的方法是,像這樣:

HighlighterGestureRecognizer * tapHighlighter = [[HighlighterGestureRecognizer alloc] init]; 

[myButton addGestureRecognizer:tapHighlighter]; 
[tapHighlighter release]; 

所以基本上你聲明它,對其進行初始化,然後將它添加。之後,您會想要釋放它,因爲addGestureRecognizer會保留它。

還只是嘗試在你的按鈕

adjustsImageWhenHighlighted = YES集?默認值是YES,但也許你在xib中改變了它。這是屬性檢查器中的「突出顯示的調整圖像」複選框:

enter image description here