创建UIBarButtonItem扩展

本人是作ios的之前一直用oc开发,现在摸索swift 虽然有点晚,用的oc代码转换成swift的可能存在瑕疵。欢迎提出问题一起学习进步。

上代码:

创建UIBarButtonItem扩展_第1张图片

import Foundation

import UIKit

extension UIBarButtonItem{

class public func      itemWithTarget(target:Any?,action:Selector,image:String,highimage:String) ->UIBarButtonItem{

let btn:UIButton = UIButton.init(type: UIButtonType.custom) btn.setBackgroundImage(UIImage.init(named: image), for: UIControlState.normal) btn.setBackgroundImage(UIImage.init(named: highimage), for: UIControlState.highlighted) var rect:CGRect = CGRect.zero

rect.size = (btn.currentBackgroundImage?.size)!

btn.frame = rect btn.addTarget(target, action: action, for: UIControlEvents.touchUpInside) return UIBarButtonItem.init(customView: btn) } }

(在控制器里)调用:(我这边定义的是返回按钮)

viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.itemWithTarget(target: self, action: #selector(back), image:"返回", highimage:"ss")

@objc private func back()

{ self.popToRootViewController(animated: true); }

我写的代码不一定对,但是能运行!

你可能感兴趣的:(创建UIBarButtonItem扩展)