仿抖音底部 Tabbar UI
支持首页滚动
Swift5仿抖音底部Tabbar示例
高仿抖音底部Tabbar,代码简洁,可复用。
代码地址:
[Swift5仿抖音TabBar]
主要TabBar布局代码为:
func updateUI() {
let SelfWidth = self.frame.size.width
let SelfHeight = self.frame.size.height
if let dataS = dataSource {
let dataArray = dataS.tabBarViewForRows(self)
var width = SelfWidth / CGFloat(dataArray.count + 1)
let height = SelfHeight
let middleView = dataS.tabBarViewForMiddle(self, size: CGSize(width: width, height: height))
var middleIndex = Int(dataArray.count) / 2
if middleView == nil {
width = SelfWidth / CGFloat(dataArray.count)
middleIndex = 0
}
topLine = UIView(frame: CGRect(x: 0, y: 0, width: SelfWidth, height: 0.6))
topLine?.backgroundColor = UIColor.hexString(color: "#f2f2f2")
superView?.addSubview(topLine!)
var xIndex = 0
for (index, value) in dataArray.enumerated(){
xIndex = index
if xIndex >= middleIndex && middleIndex != 0 {
xIndex += 1
}
if index == middleIndex && middleIndex != 0 {
let view = UIView(frame: CGRect(x: CGFloat(middleIndex) * width, y: 0, width: width, height: height))
view.backgroundColor = UIColor.clear
view.addSubview(middleView!)
superView?.addSubview(view)
}
let btn = UIButton(type: UIButton.ButtonType.custom)
btn.frame = CGRect(x: CGFloat(xIndex) * width, y: 0, width: width, height: height)
btn.backgroundColor = UIColor.clear
let normalTitle = NSMutableAttributedString(string: value.title, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.gray])
btn.setAttributedTitle(normalTitle, for: UIControl.State.normal)
let selectTitle = NSMutableAttributedString(string: value.title, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.white])
btn.setAttributedTitle(selectTitle, for: UIControl.State.selected)
btn.addTarget(self, action: #selector(self.selectAction(sender:)),for: .touchUpInside)
btn.isSelected = false
btn.tag = index + 1
var textRect = CGRect()
let textSize = CGSize(width: 0, height: 2)
textRect = value.title.boundingRect(with: textSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16)], context: nil)
let lineView = LineView.lineView(textW: textRect.size.width, index: xIndex, supSize: CGSize(width: width, height: height))
lineView.tag = index + 1 + 100
superView?.addSubview(btn)
superView?.addSubview(lineView)
}
}
self.addSubview(superView!)
}
func selectTabBar(index: Int) {
if index == selectIndex {
return
}
if let btn: UIButton = superView?.viewWithTag(index) as? UIButton {
if let btn: UIButton = superView?.viewWithTag(selectIndex) as? UIButton {
btn.isSelected = false
}
btn.isSelected = true
updateBottomView(index: index)
selectIndex = index
}
}
支持普通类型的TabBar
override func tabBarViewForMiddle(_ tabBarView: XYTabBarView, size: CGSize) -> UIView? {
return nil
}