您的位置:首页 > 产品设计 > UI/UE

做一个Active To

2015-11-23 16:04 375 查看
2015年11月12日 星期四 iOS第9天

做一个类似iPhone上的那个小圆点,就是Active Touch 的小东西

主要代码:

ViewController类:

#define ARC4RANDOM_MAX 0x100000000
#define k_diameter 40   // 设置小圆点的直径

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];

//  创建一个SliderImageView对象
SliderImageView *_iTouch = [[SliderImageView alloc]initWithFrame:CGRectMake(-k_diameter / 2.0f, floorf(((double)arc4random() / ARC4RANDOM_MAX) * k_ScreenHeight - k_diameter) , k_diameter, k_diameter)]; // 随机放置iTouch于视图左侧
[self.view addSubview:_iTouch];

_iTouch.layer.cornerRadius = k_diameter / 2.0f;     // 设置圆角半径为直径的一半即可得到圆
[_iTouch setUserInteractionEnabled:YES];            // 打开人机交互
[_iTouch setBackgroundColor:[UIColor cyanColor]];   // 设置背景颜色
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end


SliderImageView类:

#define k_ScreenHeight [UIScreen mainScreen].bounds.size.height
#define k_ScreenWidth [UIScreen mainScreen].bounds.size.width

@interface SliderImageView : UIImageView

@end
@implementation SliderImageView

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];           // 创建一个触摸点
CGPoint point = [touch locationInView:self];    // 获取触摸点的坐标

self.center = [self convertPoint:point toView:self.superview];  // 将point相对于self的坐标转换为self.superview的坐标
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[UIView animateWithDuration:0.20f animations:^{ // 视图动作,判断当前的x坐标离左右两侧哪边近就停靠在哪边
self.frame = CGRectMake(((self.frame.origin.x <= k_ScreenWidth / 2) ? 0 : k_ScreenWidth) - self.frame.size.width / 2.0f, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息