【问题标题】:how to let the touchesMoved only control one view?如何让 touchesMoved 只控制一个视图?
【发布时间】:2011-07-17 15:43:21
【问题描述】:

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

【问题讨论】:

    标签: objective-c ios event-handling uibutton


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,但是还是不行。按钮现在不能移动了。谢谢
    • if(CGRectContainsPoint(theButton.frame, touchBegan)) { buttonTouched = YES; } 这里的代码不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多