我在视图上创建了一个UIButton,我想让touchesMoved只控制UIButton,而不是整个视图
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint touchMoved = [touch locationInView:self.view];
}
我想这样做如果我触摸UIButton,然后UIButton可以用我的手指移动,如果我触摸其他视图并且我的手指在屏幕上移动,UIButton什么都不做。这意味着功能touchesMoved只有UIButton的角色,所以我怎么能做到呢?由于
我假定您显示的代码发生在您的自定义视图控制器子类中,并且UIButton
是其视图的子视图。
在类中定义一个简单的BOOL
,首先将其设置为NO
。然后在事件处理方法中更新它。
// .h
BOOL buttonTouched;
// .m
// in the viewDidLoad
buttonTouched = NO;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// test wether the button is touched
UITouch *touch = [touches anyObject];
CGPoint touchBegan = [touch locationInView:self.view];
if(CGRectContainsPoint(theButton.frame, touchBegan) {
buttonTouched = YES;
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if(buttonTouched) {
// do it here
UITouch *touch = [touches anyObject];
CGPoint touchMoved = [touch locationInView:self.view];
CGRect newFrame = CGRectMake(touchMoved.x,
touchMoved.y,
theButton.frame.width,
theButton.frame.height);
theButton.frame = newFrame;
}
}
// when the event ends, put the BOOL back to NO
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
buttonTouched = NO;
}