No.6 ios--ui--codereview 按住view拖动view可以改变view的位置

ViewController.m


//
//  ViewController.m
//  shijian
//
//  Created by admin on 15-2-25.
//  Copyright (c) 2015年 admin. All rights reserved.
//


#import "ViewController.h"
#import "TouchView.h"
@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    TouchView *view = [[TouchView alloc] initWithFrame:CGRectMake(20, 20, 200, 200)];
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];
    [view release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


TouchView.h


#import <UIKit/UIKit.h>


@interface TouchView : UIView
{
    CGPoint _touchPoint;
}




@end


TouchView.m


#import "TouchView.h"


@implementation TouchView


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    self.backgroundColor = [UIColor colorWithRed:(arc4random() % 256)/255.0 green:(arc4random() % 256)/255.0 blue:(arc4random() % 256)/255.0 alpha:1.0];
    
    UITouch *touch = [touches anyObject];
    CGPoint startPoint = [touch locationInView:self];
    _touchPoint = startPoint;
    NSLog(@"%f, %f", startPoint.x, startPoint.y);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint movePonit = [touch locationInView:self];
    
    CGFloat _offx = movePonit.x - _touchPoint.x;
    CGFloat _offy = movePonit.y - _touchPoint.y;
    
    CGFloat _lox = _offx + self.center.x;
    CGFloat _loy = _offy + self.center.y;
    self.center = CGPointMake(_lox, _loy);
    
    
    NSLog(@"%f, %f", movePonit.x, movePonit.y);
}




@end


你可能感兴趣的:(ios,UI,拖动view的位置)