繁体   English   中英

在主屏幕 iPhone 中拖动 UIView 之类的应用程序

[英]drag UIView like apps in the home screen iPhone

我有一个视图控件,我打算在里面放置一些控件,例如按钮文本框等...我可以沿 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;

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

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

在此处输入图像描述

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM