話不多說,效果如下:
全部程式碼已上傳至 ---Github--- 歡迎 Star.##使用
class HKTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
...
viewControllers = [vc0, vc1, vc2]
/**
* imageName 圖片名稱
* title 文字
* distance 最大的偏移距離
* mini_x_Coef 小圖x偏移係數
* mini_y_Coef 小圖y偏移係數
*/
let item = HKTabBarModel(imageName: "recent", title: "訊息", distance: 10, mini_x_Coef: 0.2, mini_y_Coef: 0.4)
let item1 = HKTabBarModel(imageName: "buddy", title: "聯絡人")
let item2 = HKTabBarModel(imageName: "qworld", title: "動態", distance: 10, mini_x_Coef: -0.2, mini_y_Coef: 0.2)
// let tabbar = HKTabBar(items: [item, item1, item2])
// tabbar.hk_delegate = self
let tabbar = HKTabBar(items: [item, item1, item2]) { (btn, index) in
print(btn?.title ?? "title")
self.selectedIndex = index
}
self.setValue(tabbar, forKey: "tabBar")
}
}
//extension HKTabBarViewController: HKTabBarDelegate {
// func hk_tabBar(_ tabBar: HKTabBar, didSelect item: HKDragButton, index: Int) {
// self.selectedIndex = index
// }
//}
複製程式碼
##分析
我們分析動畫效果可以猜出,QQ的TabBar 是在按鈕上放置了兩張圖片.在拖拽時兩張圖片分別有著不同的偏移量.(在QQ的資源包裡發現了,這樣的圖片,證實確實是兩張圖片而成).
####工作 所以呢,實現這個效果有幾個重點(重點不是難點 都很簡單),
######1.讓按鈕響應拖拽(pan)手勢,並能根據手指的位置計算兩張圖片應有的偏移 程式碼如下
//distance 最大偏移量
// dragButton_x & dragButton_y 需要偏移的量
//
var point = pan.location(in: self)
point = CGPoint(x: point.x - bounds.size.width * 0.5, y: point.y - bounds.size.height * 0.5)
let X = point.x
let Y = point.y
let R = sqrt(pow(X , 2) + pow(Y , 2))
let scale = R / distance
self.dragButton_x = X / scale
self.dragButton_y = Y / scale
複製程式碼
######2.更改圖片位置
//mini_x_Coef ,mini_y_Coef 是小圖的偏移差異,為了造成"立體(詭異)"的效果
private func dragIcon() {
let x = (bounds.size.width - imageView_big.bounds.size.width) * 0.5 + dragButton_x
let y = (bounds.size.height - imageView_big.bounds.size.height) * 0.5 + dragButton_y
self.imageView_big.frame = CGRect(x: x,
y: y,
width: self.imageView_big.bounds.size.width,
height: self.imageView_big.bounds.size.height
)
self.imageView_mini.frame = CGRect(x: x + self.dragButton_x * mini_x_Coef,
y: y + self.dragButton_y * mini_y_Coef,
width: self.imageView_big.bounds.size.width,
height: self.imageView_big.bounds.size.height
)
}
複製程式碼
######3.放手歸位
//讓計算出的偏移量位0 即可
self.dragButton_y = 0
self.dragButton_x = 0
UIView.animate(withDuration: 0.3) {
self.imageView_big.frame = CGRect(x: 0.0 , y: 0.0, width: self.itemW, height: self.itemH - 15.0)
self.imageView_mini.frame = CGRect(x: 0.0 , y: 0.0, width: self.itemW, height: self.itemH - 15.0)
}
複製程式碼
######4.選中動畫
//首先更改圖片
...
//最簡單的動畫
UIView.animate(withDuration: 0.2, animations: {
self.imageView_big.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
self.imageView_mini.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
}) { (_) in
UIView.animate(withDuration: 0.2, animations: {
self.imageView_big.transform = CGAffineTransform(scaleX: 1, y: 1)
self.imageView_mini.transform = CGAffineTransform(scaleX: 1, y: 1)
})
}
複製程式碼
以上便是 <實現QQ的TabBar拖拽動效> 的主要程式碼 Github