玩转【斗鱼直播APP】系列之首页导航栏设置作者:小码哥教育重点掌握内容导航栏添加Items给系统的类扩充方法扩充便利构造函数效果展示在iOS开发中,导航栏的设置是必不可少的一部分。通常导航栏中会放很多的UIBarButtonItem,以方便用于操作对应的功能斗鱼首页导航条展示直接实现(最low方式)不管是左侧logo的Item,还是右侧的三个Item都是有点击效果的。因此在实现时,最好创建UIButton,通过给UIButton设置图片来实现。并且让UIButton作为UIBarButtonItem的customView实现代码如下://MARK:-设置导航栏内容extensionHomeViewController{//MARK:设置导航栏privatefuncsetupNavigationBar(){setupNavigationLeftBar()setupNavigationRightBar()}privatefuncsetupNavigationLeftBar(){letbtn=UIButton()btn.setImage(UIImage(named:"logo"),forState:.Normal)btn.sizeToFit()btn.addTarget(self,action:#selector(self.leftItemClick),forControlEvents:.TouchUpInside)navigationItem.leftBarButtonItem=UIBarButtonItem(customView:btn)}privatefuncsetupNavigationRightBar(){//1.确定UIButton的尺寸letsize=CGSize(width:40,height:44)//2.创建历史的ItemlethistoryBtn=UIButton()historyBtn.setImage(UIImage(named:"image_my_history"),forState:.Normal)historyBtn.setImage(UIImage(named:"image_my_history_click"),forState:.Highlighted)historyBtn.addTarget(self,action:#selector(self.historyItemClick),forControlEvents:.TouchUpInside)historyBtn.frame=CGRect(origin:CGPointZero,size:size)lethistoryItem=UIBarButtonItem(customView:historyBtn)//3.创建搜索的ItemletsearchBtn=UIButton()searchBtn.setImage(UIImage(named:"btn_search"),forState:.Normal)searchBtn.setImage(UIImage(named:"btn_search_clicked"),forState:.Highlighted)searchBtn.addTarget(self,action:#selector(self.searchItemClick),forControlEvents:.TouchUpInside)searchBtn.frame=CGRect(origin:CGPointZero,size:size)letsearchItem=UIBarButtonItem(customView:searchBtn)//4.创建二维码的ItemletqrcodeBtn=UIButton()qrcodeBtn.setImage(UIImage(named:"image_scan"),forState:.Normal)qrcodeBtn.setImage(UIImage(named:"image_scan_click"),forState:.Highlighted)qrcodeBtn.addTarget(self,action:#selector(self.qrCodeItemClick),forControlEvents:.TouchUpInside)qrcodeBtn.frame=CGRect(origin:CGPointZero,size:size)letqrcodeItem=UIBarButtonItem(customView:qrcodeBtn)navigationItem.rightBarButtonItems=[historyItem,searchItem,qrcodeItem]}//MARK:导航栏的事件处理@objcprivatefuncleftItemClick(){print("点击了logo")}@objcprivatefuncqrCodeItemClick(){print("点击了二维码")}@objcprivatefuncsearchItemClick(){print("点击了搜索")}@objcprivatefunchistoryItemClick(){print("点击了历史")}}优化上述代码(系统类扩充方法)上述方式虽然实现了功能,但是我们发现重复代码太多。并且如果其他地方也用到类似的功能,还是要写大量代码。最好的方式就是进行抽取?如何抽取呢?在OC中我们通常给系统的类抽取分类,在分类中给系统的类扩充方法Swift也是类似,只是Swift使用extension,表示对系统的类进行扩充比如我们给系统的类抽取类方法,代码如下:给系统类扩充类方法extensionUIBarButtonItem{classfunccreateBarButtonItem(imageName:String,highImageName:String="",size:CGSize=CGSizeZero,target:AnyObject?=nil,action:Selector=nil)->UIBarButtonItem{//1.创建UIButtonletbtn=UIButton(type:.Custom)//2.给UIButton设置属性btn.setImage(UIImage(named:imageName),forState:.Normal)ifhighImageName!=""{btn.setImage(UIImage(named:highImageName),forState:.Highlighted)}//3.设置尺寸ifsize==CGSizeZero{btn.sizeToFit()}else{btn.frame=CGRect(origin:CGPointZero,size:size)}//4.监听点击btn.addTarget(target,action:action,forControlEven...