import Foundation
import UIKit
extension UIBarButtonItem {
class func createFrom(_ colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.setImage(colorfulImage, for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
button.addTarget(target, action: action, for: .touchUpInside)
button.imageEdgeInsets = UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 44).isActive = true
button.heightAnchor.constraint(equalToConstant: 44).isActive = true
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
class func createFrom(namedImage: String, target: AnyObject, action: Selector) -> UIBarButtonItem {
let colorfulImage = UIImage.init(named: namedImage, in: Bundle(for: ItemViewController.self), compatibleWith: nil)
let button = UIButton(type: .custom)
button.setImage(colorfulImage, for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
button.addTarget(target, action: action, for: .touchUpInside)
button.imageEdgeInsets = UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 44).isActive = true
button.heightAnchor.constraint(equalToConstant: 44).isActive = true
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
}
Easy extension to create UIBarButtonItem from images
31 sec read