[英]Custom UIControl and Gesture Recognizer
我試圖創建一個類似於滑塊的自定義UIControl。
此控件將是視圖的子視圖,該視圖還具有附加的輕擊手勢識別器。
現在的問題是,此輕擊手勢識別器會取消發送給我的控件的觸摸。 有沒有一種方法可以從我的控件代碼中覆蓋它?
如果我查看iOS中的標准控件,似乎UIButton可以替代輕擊手勢識別器,而UISlider則沒有。 因此,如果我將自定義控件替換為UIButton,則輕擊手勢識別器不會觸發其動作,但是如果我將其替換為滑塊,則會觸發它。
編輯 :我在Xcode中做了一個小項目,可以在其中玩耍。在這里下載https://dl.dropboxusercontent.com/u/165243/TouchConcept.zip並嘗試對其進行更改,以便
編碼:
// inherit from UIButton will give the wanted behavior, inherit from UIView (or UIControl) gives
// touchesCancelled by the gesture recognizer
@interface UICustomControl : UIView
@end
@implementation UICustomControl
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{ NSLog(@"touchesBegan"); }
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{ NSLog(@"touchesMoved"); }
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{ NSLog(@"touchesEnded"); }
-(void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{ NSLog(@"touchesCancelled"); }
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(logTap:)];
[self.view addGestureRecognizer:tapRecognizer];
UIView *interceptingView = [[UICustomControl alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
interceptingView.userInteractionEnabled = YES;
interceptingView.backgroundColor = [UIColor yellowColor];
[self.view addSubview: interceptingView];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) logTap: (id) sender
{
NSLog(@"gesture recognizer fired");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
您可以使用“取消視圖中的觸摸”屬性將手勢識別器配置為不取消其附加視圖中的觸摸:
myGestureRecognizer.cancelsTouchesInView = NO;
我有點晚了,但是對於那些(像我一樣)陷入這個問題的人,我使用了替代解決方案:
使用手勢識別器的委托。
UITapGestureRecognizer *tapGestRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissInfoBox:)];
tapGestRec.delegate = self;
[self.view addGestureRecognizer:tapGestRec];
然后,當手勢識別器要處理/吞咽觸摸時,應在shouldReceiveTouch委托函數中進行某種命中測試。
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
CGPoint location = [touch locationInView:self.view];
return !CGRectContainsPoint(self.myCustomControl.frame, location) && !CGRectContainsPoint(self.myOtherCustomControl.frame, location);
}
我在ViewController中完成了所有這些操作,因此UIControl不必知道任何同級視圖,並且手勢識別器不會從我的自定義控件中“竊取”水龍頭,而僅處理“未捕獲”的水龍頭。
同樣,通過這種方式,您不會同時觸發手勢識別器和自定義控件,而cancelsTouchesInView會發生這種情況。
順便說一句,也許它可以與UIButton一起使用,因為UIButton在內部使用了手勢識別器? 我認為他們彼此了解,而UIControls和識別器則不了解。 雖然不確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.