|
| 1 | +// |
| 2 | +// ESUIBarButtonItem+Extension.swift |
| 3 | +// ESUIHelper |
| 4 | +// |
| 5 | +// Created by Emil Karimov on 12/06/2020 |
| 6 | +// Copyright © 2020 ESKARIA LLC. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | + |
| 10 | +import UIKit |
| 11 | + |
| 12 | +public struct ESBarButtonItem { |
| 13 | + let icon: UIImage? |
| 14 | + let target: AnyObject? |
| 15 | + let action: Selector? |
| 16 | + let accessibilityName: String |
| 17 | +} |
| 18 | + |
| 19 | +extension UIBarButtonItem { |
| 20 | + |
| 21 | + /// Get compacted barbutton items |
| 22 | + /// |
| 23 | + /// - Parameter items: array of struct for buttons |
| 24 | + /// - Returns: only one barButton item |
| 25 | + public static func items(_ items: [DHBarButtonItem]) -> UIBarButtonItem { |
| 26 | + |
| 27 | + let stackView = UIStackView() |
| 28 | + stackView.axis = .horizontal |
| 29 | + stackView.distribution = .fillEqually |
| 30 | + stackView.spacing = 0 |
| 31 | + stackView.frame = CGRect(x: 0, y: 0, width: 44 * items.count, height: 44) |
| 32 | + |
| 33 | + for item in items { |
| 34 | + |
| 35 | + let button = UIButton(type: .custom) |
| 36 | + let image = item.icon |
| 37 | + button.setImage(image, for: .normal) |
| 38 | + if let target = item.target, let action = item.action { |
| 39 | + |
| 40 | + button.addTarget(target, action: action, for: .touchUpInside) |
| 41 | + } |
| 42 | + button.accessibilityLabel = item.accessibilityName |
| 43 | + |
| 44 | + button.heightAnchor.constraint(equalToConstant: 44).isActive = true |
| 45 | + button.widthAnchor.constraint(equalToConstant: 44).isActive = true |
| 46 | + stackView.addArrangedSubview(button) |
| 47 | + } |
| 48 | + |
| 49 | + return UIBarButtonItem(customView: stackView) |
| 50 | + } |
| 51 | + |
| 52 | + public static func item(icon: UIImage?, target: AnyObject?, action: Selector?, accessibilityName: String, width: CGFloat = 44, height: CGFloat = 44) -> UIBarButtonItem { |
| 53 | + |
| 54 | + let button = UIButton(type: .custom) |
| 55 | + button.setImage(icon, for: .normal) |
| 56 | + if let target = target, let action = action { |
| 57 | + |
| 58 | + button.addTarget(target, action: action, for: .touchUpInside) |
| 59 | + } |
| 60 | + button.accessibilityLabel = accessibilityName |
| 61 | + |
| 62 | + if #available(iOS 11, *) { |
| 63 | + |
| 64 | + button.heightAnchor.constraint(equalToConstant: height).isActive = true |
| 65 | + button.widthAnchor.constraint(equalToConstant: width).isActive = true |
| 66 | + |
| 67 | + } else { |
| 68 | + |
| 69 | + button.frame = CGRect(x: 0, y: 0, width: width, height: height) |
| 70 | + } |
| 71 | + let barButton = UIBarButtonItem(customView: button) |
| 72 | + return barButton |
| 73 | + } |
| 74 | +} |
0 commit comments