如何让touchesMoved只控制一个视图?

时间:2011-07-17 15:43:22

标签: objective-c ios event-handling uibutton

我在视图上创建了一个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的作用,那么我该怎么做呢?感谢

1 个答案:

答案 0 :(得分:5)

我假设您显示的代码发生在自定义视图控制器子类中,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;
}