因為項目中添加這個功能然后研究了一下,記錄下供以后回顧
[參考]http://www.myexception.cn/operating-system/1924022.html
懸浮按鈕的創(chuàng)建和使用
- 通過UIButton直接創(chuàng)建
- 通過UIWindow創(chuàng)建按鈕
一. 通過UIButton直接創(chuàng)建
原理:用到了UIButton 的UIControlEventTouchDragInside 這個屬性,在拖動的時候的時候重新設置UIButton的中心的點的位置
附部分事件:
UIControlEventTouchDragInside
當一次觸摸在控件窗口內拖動時。
UIControlEventTouchDragOutside
當一次觸摸在控件窗口之外拖動時。
UIControlEventTouchDragEnter
當一次觸摸從控件窗口之外拖動到內部時。
UIControlEventTouchDragExit
當一次觸摸從控件窗口內部拖動到外部時。
UIControlEventTouchUpInside
所有在控件之內觸摸抬起事件。
部分代碼:
[self.btn addTarget:self action:@selector(dragMoving:withEvent: )forControlEvents: UIControlEventTouchDragInside];
- (void) dragMoving: (UIButton *) c withEvent:ev
{
self.a=1;
c.center = [[[ev allTouches] anyObject] locationInView:self.view];
}
二. 通過UIWindow創(chuàng)建按鈕
原理:通過創(chuàng)建一個新的UIWindow,在頂上添加重寫之后的UIButton在重寫的UIButton里面設置各種的便宜量保證按鈕能夠依附邊界。因為默認的情況下只能存在一個Window我們還需要設置windowLevel。
部分代碼:
// 開始觸摸,記錄觸點位置用于判斷是拖動還是點擊
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
UITouch *touch = [touches anyObject];
_startPos = [touch locationInView:_rootView];
}
手指按住移動過程,通過懸浮按鈕的拖動事件來拖動整個懸浮窗口
*/
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// 獲得觸摸在根視圖中的坐標
UITouch *touch = [touches anyObject];
CGPoint curPoint = [touch locationInView:_rootView];
// 移動按鈕到當前觸摸位置
self.superview.center = curPoint;
}
拖動結束后使懸浮窗口吸附在最近的屏幕邊緣
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 獲得觸摸在根視圖中的坐標
UITouch *touch = [touches anyObject];
CGPoint curPoint = [touch locationInView:_rootView];
switch (minDir) {
case LEFT:
{
[UIView animateWithDuration:0.3 animations:^{
self.superview.center = CGPointMake(self.superview.frame.size.width/2, self.superview.center.y);
}];
break;
}
case RIGHT:
{
[UIView animateWithDuration:0.3 animations:^{
self.superview.center = CGPointMake(ScreenW - self.superview.frame.size.width/2, self.superview.center.y);
}];
break;
}
}