首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 懸浮底部按鈕實作:自動佈局與視圖層級管理

     編輯:程式設計綜合問答

需求

按鈕固定在螢幕底部,不隨內容捲動,類似「提問」浮動按鈕。

方案一:Auto Layout 釘住底部 (單一 ViewController)

let floatingButton = UIButton(type: .system)
floatingButton.setTitle("提問", for: .normal)
floatingButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(floatingButton)

NSLayoutConstraint.activate([
    floatingButton.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    floatingButton.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    floatingButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
    floatingButton.heightAnchor.constraint(equalToConstant: 50)
])

方案二:加在 UIWindow 上 (全局懸浮,跨控制器)

if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
    window.addSubview(floatingButton)
    // 同樣加約束釘住 window 底部
}

方案三:使用 UITabBarController 自帶 TabBar

若應用為分頁結構,直接自訂 UITabBar 項目圖片/文字,原生固定底部,無需額外佈局。

進階:安全區域適配 (iPhone X 系列)

// 關鍵:使用 safeAreaLayoutGuide.bottomAnchor 而非 view.bottomAnchor
// 避免被 Home Indicator 遮擋
button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true

動畫效果:捲動時隱藏/顯示

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offset = scrollView.contentOffset.y
    let shouldHide = offset > lastOffset && offset > 100 // 向下捲動超過閾值
    UIView.animate(withDuration: 0.3) {
        self.floatingButton.transform = shouldHide ? CGAffineTransform(translationX: 0, y: 100) : .identity
    }
    lastOffset = offset
}

注意

  • 加在 window 需手動管理生命週期,避免記憶體洩漏。
  • 若使用 UICollectionView/UITableView,設定 contentInset.bottom = buttonHeight 確保最後一筆資料不被遮擋。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved