Floating Button

Molder
4 min readSep 6, 2021

之前在一些電商APP首頁都會看到一顆帶有圖案的浮動按鈕,就像iPhone那顆輔助觸控一樣,可以推上推下推左推右,點下去還有其他功能,蠻有意思的。

限制:iOS 3以上 (基本無限制)

實作

  1. 首先要先建一個客製化 FloatingButtonView.swift 繼承 UIView
  2. 設定 FloatingButtonView frame 並加入 UIPanGestureRecognizer
  3. 在 FloatingButtonView 裡建立兩個 UIButton 並設定好 Constraints (UIButton 如果想換成 UIImageView 也是可以的)
  4. 兩個 UIButton 分別加入各自 click 事件 (如範例:一個是close用,另一個是外開瀏覽器用)
  5. 這時候再來寫剛剛 FloatingButtonView 的 UIPanGestureRecognizer 事件約束
/// 拖曳手勢@objc func handlePanGesture(_ gesture: UIPanGestureRecognizer) {// 取得手勢位置let location = gesture.location(in: targetView)// 移動中if gesture.state == .changed {  self.center = location// 移動結束} else if gesture.state == .ended {  var lineBtnRect = self.frame// 左邊if location.x < screenWidth/2 {  lineBtnRect.origin.x = 0// 右邊} else {  lineBtnRect.origin.x = screenWidth - self.frame.width}// 上邊if location.y - self.frame.height/2 < 44 {  lineBtnRect.origin.y = 44// 下邊} else if location.y + self.frame.height/2 > screenHeight - 44 {  lineBtnRect.origin.y = screenHeight - 44 - self.frame.height - 10}UIView.animate(withDuration: 0.2, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: {  self.frame = lineBtnRect}, completion: nil)}}

完整版

6. 到這裡基本上客製化 FloatingButtonView 已經準備好了,再來就是讓他顯示在畫面上,讓我們回到 ViewController,在 viewDidLoad 裡建立FloatingButtonView() 物件

let floatingButton = FloatingButtonView()floatingButton.delegate = selffloatingButton.addFloatingButton(target: self.view)

7. 因為FloatingButtonView有使用delegate 回傳使用者有做點擊事件,所以在 ViewController 要繼承 FloatingButtonViewDelegate 並實作

func btnViewAciton()

8. 在範例裡是外開瀏覽器,這裡可以自由發揮,看要做什麼事件都可以。

9. 實作完 FloatingButtonViewDelegate 後就完成了。可以Run 實機看看效果了。

--

--