動(dòng)機(jī)
關(guān)于自定義 TabBar,早就有過很多討論,開源網(wǎng)站上也有很多造好的輪子,多半是純代碼實(shí)現(xiàn)有個(gè)性的 TabBar,當(dāng)然我們可以很方便的使用它。周末閑著沒事干,自己也寫了一下,模仿今日頭條的 TabBar 效果,實(shí)現(xiàn)方式是Storyboard + 代碼。
效果圖
	
實(shí)現(xiàn)步驟在 Storyborad 上搭建項(xiàng)目基礎(chǔ)結(jié)構(gòu)
	
在界面上設(shè)置每個(gè) TabBarItem 的相關(guān)屬性
	
需要自定義的 item 不需要在界面上設(shè)置。
自定義 UITabBarViewController
目的
	替換默認(rèn)的 UITabBar
	處理 發(fā)布按鈕(中間那個(gè)加號(hào)按鈕)點(diǎn)擊事件
主要代碼
替換 UITabBar,監(jiān)聽點(diǎn)擊事件
override func viewDidLoad() {  super.viewDidLoad()  // 替換 tabbar  let _tabBar = TabBar()  // 監(jiān)聽按鈕點(diǎn)擊事件  _tabBar.handleBtnReleaseClick(self, action: #selector(btnReleaseClick))  setValue(_tabBar, forKey: "tabBar")}自定義 UITabBar
目的
	自定義 UITabBar,替換掉 Storyboard 上默認(rèn)生成的 TabBarItem
	處理 發(fā)布按鈕(中間那個(gè)加號(hào)按鈕)點(diǎn)擊事件
主要代碼
刪除占位“按鈕”,添加自定義按鈕
// MARK: 刪除占位“按鈕”,添加自定義按鈕override func layoutSubviews() {  super.layoutSubviews()  btnRelease.backgroundColor = UIColor.white  // 過濾掉 _UIBarBackground 類型的對(duì)象,只保留 UITabBarButton 類型的對(duì)象  let tabbarButtonList = iews.filter{NSStringFromClass(type(of: $0)) == abBarButton"}  // 取出需要?jiǎng)h除的“按鈕”(經(jīng)測(cè)試,知道中間那個(gè)加號(hào)按鈕的下標(biāo)是2)  let tmpView = tabbarButtonList[safe: 2]  // 把默認(rèn)生成的從父容器中移除  tmpView?.removeFromSuperview()  let x = (InnerConst.ScreenW - btnRelease.w) * 0.5  let y = InnerConst.ButtonOffsetY  btnRelease.origin = CGPoint(x: x, y: y)  addSubview(btnRelease)}處理默認(rèn)情況下,按鈕超出 TabBar 以外區(qū)域不能點(diǎn)擊問題
// MARK: 處理默認(rèn)情況下,按鈕超出 TabBar 以外區(qū)域不能點(diǎn)擊問題override func hitTest(_ point: CGPoint, with event: UIEvent?) -View? {  if isHidden == false {    let newPoint = convert(point, to: btnRelease)    if btnRelease.point(inside: newPoint, with: event) {      return btnRelease    }    return super.hitTest(point, with: event)  }  return super.hitTest(point, with: event)}按鈕點(diǎn)擊事件委托給調(diào)用方
func handleBtnReleaseClick(_ target: AnyObject?, action: Selector) {  btnRelease.addTarget(target, action: action, for: .touchUpInside)}代碼寫到這里,一個(gè)類似于今日頭條的 UITabBar(主要是中間那個(gè)按鈕)差不多造出來了。以上部分貼出來的是個(gè)人認(rèn)為比較關(guān)鍵的代碼,有問題可以討論,目的是用最簡單的方式、最少的代碼實(shí)現(xiàn)需求。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注