//
// UIButtonExtension.swift
// ZYFWB
//
// Created by fe on 2017/3/8.
// Copyright © 2017年 fe. All rights reserved.
//import UIKit//UIButton的类方法扩展
extension UIButton {//这里的类方法相当于OC中的加号方法class func creatButtonWithImageName(imageName : String , bgImageName : String) -> UIButton {//创建按钮let button = UIButton()//设置按钮的背景图片button.setBackgroundImage(UIImage(named: bgImageName), for: UIControlState.normal)button.setBackgroundImage(UIImage(named: bgImageName + "_highlighted"), for: UIControlState.highlighted)//设置按钮的图片button.setImage(UIImage(named: imageName), for: UIControlState.normal)button.setImage(UIImage(named: imageName + "_highlighted"), for: UIControlState.highlighted)//按照背景图片初始化按钮尺寸button.sizeToFit()//返回按钮return button}/*convenience : 便利,使用convenience修饰的构造函数叫做便利构造函数便利构造函数通常在对系统的类进行构造函数的扩充时使用便利构造函数的特点1.便利构造函数通常是写在extension中2.便利构造函数init前面需要加载convenience3.在便利构造函数中需要明确调用self.init*/convenience init(imageName : String , bgImageName : String) {self.init()//设置按钮的图片setImage(UIImage(named: imageName), for: UIControlState.normal)setImage(UIImage(named: imageName + "_highlighted"), for: UIControlState.highlighted)//设置按钮的背景图片setBackgroundImage(UIImage(named: bgImageName), for: UIControlState.normal)setBackgroundImage(UIImage(named: bgImageName + "_highlighted"), for: UIControlState.highlighted)//按照背景图片初始化按钮尺寸sizeToFit()}}
//
// MainViewController.swift
// ZYFWB
//
// Created by fe on 2017/3/7.
// Copyright © 2017年 fe. All rights reserved.
//import UIKitclass MainViewController: UITabBarController {//懒加载tabBar选中图片的数组lazy var selectImages = ["tabbar_home","tabbar_message_center","","tabbar_discover","tabbar_profile"]//懒加载中间的发布按钮(使用类方法)//lazy var composeBtn : UIButton = UIButton(imageName : "tabbar_compose_icon_add" , bgImageName : "tabbar_compose_button")//懒加载中间的发布按钮(使用构造方法)lazy var composeBtn : UIButton = UIButton.creatButtonWithImageName(imageName : "tabbar_compose_icon_add" , bgImageName : "tabbar_compose_button")//系统调用函数override func viewDidLoad() {super.viewDidLoad()//设置发布按钮setupComposeBtn()}//系统调用函数override func viewWillAppear(_ animated: Bool) {super.viewWillAppear(animated)//调整tabBar的显示细节问题需要在该方法中,如果在viewDidLoad中调整,则在该方法中会被调整回来setupTabBarItems()}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}}// MARK:-设置UI界面
extension MainViewController {func setupComposeBtn() {//设置发布按钮位置composeBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.frame.size.height * 0.5)//添加发布按钮到tabBartabBar.addSubview(composeBtn)}//调整tabbaritemsfunc setupTabBarItems() {//遍历tabBarItemfor i in 0..<tabBar.items!.count{//拿到itemlet item = tabBar.items![i]//如果i为2则控制item不能点击if i == 2 {item.isEnabled = falsecontinue}//设置item的选中图片item.selectedImage = UIImage(named: selectImages[i] + "_selected")}}
}