建立可移動的視圖

來源:互聯網
上載者:User

標籤:建立可移動式圖

1.首先建立一個根視圖控制器(引入標頭檔)

原代碼:

 // 設定根視圖控制器    MainViewController *mainVC=[[MainViewController alloc] init];    _window.rootViewController =mainVC;    [mainVC release];
2.在視圖控制器中建立一個MyView的 UIView的子類(引入標頭檔)

原代碼:

///建立一個MyView;    MyView *myView=[[MyView alloc] initWithFrame:CGRectMake(100, 200, 150, 40)];    myView.backgroundColor =[UIColor redColor];    [self.view addSubview:myView];    [myView release];
3.在MyView中建立一個方法從上面的代碼可以看出:

touches相當一個集合 點擊一下 相當於集合中只有一個元素

4.在觸摸開始方法中擷取初始位置:(1).用 touches.count 可以測出touches中元素的個數
 NSLog(@"%ld",touches.count);
(2).用 anyObject可以去到這個對象
UITouch *touch =[touches anyObject];
(3).通過觸摸對象擷取相應的視圖的當前的位置
self.startPoint =[touch locationInView:self];   
5.在移動方法中可以得到新的點的座標
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{    // 通過移動,找到變化,然後讓MyView也進行相應的調整,從而實現試圖隨手移動的效果    // 擷取觸摸的對象    UITouch *touch =[touches anyObject];    // 擷取移動之後的座標    CGPoint movePoint =[touch locationInView:self];    // 找座標的變化      CGFloat dx =movePoint.x -self.startPoint.x;    CGFloat dy =movePoint.y -self.startPoint.y;    // 設定視圖的移動變化    self.center =CGPointMake(self.center.x +dx, self.center.y +dy);  }  

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

建立可移動的視圖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.