Create a movable view

Source: Internet
Author: User

1. First create a root view controller (introduce header file)

Original code:

 // 设置根视图控制器    MainViewController *mainVC=[[MainViewController alloc] init];    _window.rootViewController =mainVC;    [mainVC release];
2. Create a subclass of MyView UIView in the View Controller (Introduction header file)

Original code:

///创建一个MyView;    MyView *myView=[[MyView alloc] initWithFrame:CGRectMake(10020015040)];    myView.backgroundColor =[UIColor redColor];    [self.view addSubview:myView];    [myView release];
3. Create a method in MyView you can see from the code above:

Touches quite a set click on the equivalent of only one element in the collection

4. Get the initial position in the touch Start Method: (1). Use Touches.count to measure the number of elements in the touches
 NSLog(@"%ld",touches.count);
(2). You can go to this object with Anyobject.
UITouch *touch =[touches anyObject];
(3). Get the current position of the corresponding view by touching the object
selflocationInView:self];   
5. The coordinates of the new point can be obtained in the moving method
-(void) touchesmoved: (Nsset *) touches withevent: (uievent *) event{//By moving, find the changes, and then let the myview also adjust accordingly, so as to achieve the effect of trying to move around    //Get Touch ObjectsUitouch *touch =[touches Anyobject];//Get the coordinates after the move    CgpointMovepoint =[touch Locationinview: Self];//Find coordinates change    CGFloatDX =movepoint. x- Self. StartPoint. x;CGFloatDy =movepoint. Y- Self. StartPoint. Y;//Set the change of movement of the View     Self. Center=cgpointmake ( Self. Center. x+DX, Self. Center. Y+dy); }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Create a movable view

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.