【问题标题】:drag UIView like apps in the home screen iPhone在主屏幕 iPhone 中拖动 UIView 之类的应用程序
【发布时间】:2011-07-08 01:04:15
【问题描述】:

我有一个视图控件,我打算在里面放置一些控件,例如按钮文本框等...我可以沿 x 轴拖动我的视图,例如:

1)

2)

使用以下代码:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];

    if( [touch view] == ViewMain)
    {
        CGPoint location = [touch locationInView:self.view];
        displaceX = location.x - ViewMain.center.x;        
        displaceY = ViewMain.center.y;        
        startPosX = location.x - displaceX;
    }

    CurrentTime = [[NSDate date] timeIntervalSince1970];

}


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



    UITouch *touch = [[event allTouches] anyObject];

    if( [touch view] == ViewMain)
    {
        CGPoint location = [touch locationInView:self.view];
        location.x =location.x - displaceX;
        location.y = displaceY;
        ViewMain.center = location;
    }  


}

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

    double time = [[NSDate date] timeIntervalSince1970]-CurrentTime;


    UITouch *touch = [[event allTouches] anyObject];

    if( [touch view] == ViewMain)
    {
        CGPoint location = [touch locationInView:self.view];
        location.x =location.x - displaceX;
        location.y = displaceY;
        ViewMain.center = location;
        double speed = (ViewMain.center.x-startPosX)/(time*2);
        NSLog(@"speed: %f", speed);

    }
}

不是我必须添加全局变量:

float displaceX = 0;
float displaceY = 0;
float startPosX = 0;
float startPosY = 0;
double CurrentTime;

我创建这些变量的原因是,当我开始拖动视图时,视图会从我触摸它的点移动,而不是从中间移动。

无论如何,如果我触摸按钮或图像,即使图像在背景上具有透明度,视图也不会拖动。无论视图顶部是否有图像,我都希望能够仍然能够拖动视图。我在想,也许我需要在所有东西上放置一个大的透明视图,但我需要有按钮、图像等。我希望能够像你一样拖动视图:

请注意,无论我第一次触摸应用程序/图像还是文本,我都可以拖动视图。我怎么能这样做?

【问题讨论】:

    标签: iphone objective-c ipad uiview drag


    【解决方案1】:

    我认为您的问题是,如果您在启用交互的情况下触摸 UIButton 或 UIImageView,它不会传递触摸。 对于图像,取消选中 IB 中的 User Interaction Enabledproperty。 对于导致 touchesBegan:withEvent: 等无法调用的按钮,请查看以下链接:Is there a way to pass touches through on the iPhone?

    【讨论】:

      【解决方案2】:

      您可能需要考虑使用不同的方法来解决此问题。与其尝试自己手动管理滚动内容,不如使用UIScrollView 并将pagingEnabled 属性设置为YES。这是 Apple 推荐的方法(这可能是 Springboard.app 在您上一个屏幕截图中使用的方法)。如果您是 iOS 开发人员计划的成员,请查看 UIScrollView 上的 WWDC 2010 会话以获取相关示例。我认为他们可能还在 developer.apple.com 上发布了示例代码。

      【讨论】:

        猜你喜欢
        • 2011-10-24
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多