// // ViewController.m // SortWithLabel // // Created by whunf on 16/3/3. // Copyright © 2016年 whunf. All rights reserved. // #import "ViewController.h" @interface ViewController () { NSMutableArray *array; //创建数组 } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //初始化数组 array = [[NSMutableArray alloc] init]; //调用自定义方法 [self initWithFrame]; } //方法功能:初始化控件 - (void)initWithFrame { CGFloat pointX = 0; // 记录X坐标 CGFloat pointY = 0; // 记录Y坐标 //创建20个LABEL 标签 for(int i =0;i<20;i++) { pointX = arc4random()%300; //获取0-200以内的随机数 pointY = arc4random()%300; //创建一个标签,并初始化 坐标是上面的随机坐标,大小为30 UILabel *lable = [[UILabel alloc]initWithFrame:(CGRect){pointX,pointY,30,30}]; //设置标签背景色 [lable setBackgroundColor:[UIColor blackColor]]; //设置标签名称 [lable setText:[NSString stringWithFormat:@"%d",i]]; //设置标签的TAG lable.tag = i; //设置标签颜色 lable.textColor = [UIColor whiteColor]; //设置标签的对齐方式是剧中对齐 lable.textAlignment = NSTextAlignmentCenter; //将标签添加到当前的窗体当中 [self.view addSubview:lable]; //将标签对象添加到数组当中 [array addObject:lable]; } } //方法功能: 将控件根据自身的tag大小进行从小到大排序 - (void) animationAction { //如果第一个控件y位置不是30,就将它移动过去 UILabel *labelI = array[0]; if(labelI.center.y!=30) { //动画--将控件移动到Y坐标是30的地方 [UIView animateWithDuration:2 animations:^{ labelI.center = CGPointMake(labelI.center.x, 30); }]; } for (int i =0; i<array.count; i++) { for(int j = 0;j<=i;j++) { UILabel *labelI = array[i]; UILabel *labelJ = array[j]; if(labelI.tag>labelJ.tag) { //两个数交换 UILabel *temp = array[i]; array[i] = array[j]; array[j] = temp; //动画 速度是2 [UIView animateWithDuration:2 animations:^{ //动画的过程是 将TAG值比较大的标签往后排 labelI.center = CGPointMake(labelJ.center.x, labelJ.center.y+labelJ.frame.size.height); }]; } } } } //手势事件 当点击屏幕时触发 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self animationAction]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
Demo 链接: http://pan.baidu.com/s/1baJLKE 密码: gymu