54 lines
1.4 KiB
Swift
54 lines
1.4 KiB
Swift
//
|
|
// CustomTabBar.swift
|
|
// Funny_sounds
|
|
//
|
|
// Created by 忆海16 on 2024/8/14.
|
|
//
|
|
|
|
import UIKit
|
|
|
|
|
|
class CustomTabBar: UITabBar {
|
|
private let selectedBackgroundView = UIImageView(image: UIImage(named: "tabbars"))
|
|
|
|
|
|
override func layoutSubviews() {
|
|
super.layoutSubviews()
|
|
|
|
// 将选中背景视图添加到 tabBar
|
|
if !subviews.contains(selectedBackgroundView) {
|
|
insertSubview(selectedBackgroundView, at: 0)
|
|
}
|
|
|
|
|
|
|
|
|
|
// 更新选中背景视图的位置
|
|
updateSelectedBackgroundViewPosition()
|
|
}
|
|
|
|
func updateSelectedBackgroundViewPosition() {
|
|
guard let selectedItem = self.selectedItem, let items = self.items else {
|
|
selectedBackgroundView.isHidden = true
|
|
return
|
|
}
|
|
|
|
guard let selectedIndex = items.firstIndex(of: selectedItem) else {
|
|
selectedBackgroundView.isHidden = true
|
|
return
|
|
}
|
|
|
|
let itemWidth = bounds.width / CGFloat(items.count)
|
|
let xPosition = itemWidth * CGFloat(selectedIndex)
|
|
selectedBackgroundView.frame = CGRect(x: xPosition, y: 0, width: itemWidth, height: bounds.height)
|
|
selectedBackgroundView.isHidden = false
|
|
}
|
|
|
|
|
|
override var selectedItem: UITabBarItem? {
|
|
didSet {
|
|
updateSelectedBackgroundViewPosition()
|
|
}
|
|
}
|
|
}
|