今天晚上下班回来 , 一朋友问我想把冒泡排序图形化展示出来 , 是怎样 , 我想大概也就是肉眼比较直观的吧 .既然没说用什么语言 , OC自带方法就可以实现了 , 只是在处理view上稍微麻烦点 .
#import "ViewController.h"
@interface ViewController ()
//存储所有的label
@property (strong ,nonatomic) NSMutableArray *labelsInfo;
//存储所有的X值
@property (strong, nonatomic) NSArray *positionXNew;
@end
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat width = 25.f;
CGFloat height = 25.f;
self.labelsInfo = [NSMutableArray array];
//创建10个label用于展示
for (NSInteger index = 0; index < 10; index++) {
CGFloat labelX = arc4random_uniform(self.view.bounds.size.width - width);
CGFloat labelY = arc4random_uniform(self.view.bounds.size.height - height);;
UILabel *label = [[UILabel alloc]init];
label.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0];
label.frame = CGRectMake(labelX, labelY, width, height);
label.textAlignment = NSTextAlignmentCenter;
label.text = [NSString stringWithFormat:@"%li",index];
[self.view addSubview:label];
//存储初始化数据
[self.labelsInfo addObject:@{@"obj":label,@"X":@(labelX)}];
}
//重新整理数据
NSArray *array = [self.labelsInfo valueForKey:@"X"];
array = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return obj1 > obj2;
}];
//保存所有X值
self.positionXNew = array;
}
//点击屏幕实现排序
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//重新升序赋值
for (NSInteger i = 0; i < self.labelsInfo.count; i ++) {
//线程稍作睡眠 , 看起来比较直观一些
[NSThread sleepForTimeInterval:1.f];
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *label = [self.labelsInfo valueForKey:@"obj"][i];
__block CGPoint center = label.center;
__block CGRect bounds = label.bounds;
[UIView animateWithDuration:1.f animations:^{
bounds.size.width = 25.f + i *5;
bounds.size.height = 25.f + i *5;
center.x = [self.positionXNew[i]floatValue];
center.y = self.view.bounds.size.height/2;
label.bounds = bounds;
label.center = center;
}];
});
}
});
}
//实现结果如下: