按鈕固定在螢幕底部,不隨內容捲動,類似「提問」浮動按鈕。
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)
])
if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
window.addSubview(floatingButton)
// 同樣加約束釘住 window 底部
}
若應用為分頁結構,直接自訂 UITabBar 項目圖片/文字,原生固定底部,無需額外佈局。
// 關鍵:使用 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 確保最後一筆資料不被遮擋。