iOS---懸浮按鈕的創(chuàng)建和使用


因為項目中添加這個功能然后研究了一下,記錄下供以后回顧

[參考]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;
        }
 }

GitDemo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容