標籤:建立可移動式圖
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); }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
建立可移動的視圖