簡體   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