UIBarButtonItem+Init.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // UIBarButtonItem+Init.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/3/9.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension UIBarButtonItem {
  11. convenience init(title: String?,
  12. titleColor: UIColor = .white,
  13. titleFont: UIFont = UIFont.systemFont(ofSize: 15),
  14. titleEdgeInsets: UIEdgeInsets = .zero,
  15. target: Any?,
  16. action: Selector?) {
  17. let button = UIButton(type: .custom)
  18. button.setTitle(title, for: .normal)
  19. button.setTitleColor(titleColor, for: .normal)
  20. button.titleLabel?.font = titleFont
  21. button.titleEdgeInsets = titleEdgeInsets
  22. if action != nil {
  23. button.addTarget(target, action: action!, for: .touchUpInside)
  24. }
  25. button.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
  26. // button.sizeToFit()
  27. // if button.bounds.width < 40 || button.bounds.height > 40 {
  28. // let width = 40 / button.bounds.height * button.bounds.width;
  29. // button.bounds = CGRect(x: 0, y: 0, width: width, height: 40)
  30. // }
  31. self.init(customView: button)
  32. }
  33. convenience init(image: UIImage?,
  34. selectImage: UIImage? = nil,
  35. imageEdgeInsets: UIEdgeInsets = .zero,
  36. target: Any?,
  37. action: Selector?) {
  38. let button = UIButton(type: .custom)
  39. button.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
  40. button.setImage(selectImage?.withRenderingMode(.alwaysOriginal), for: .selected)
  41. button.imageEdgeInsets = imageEdgeInsets
  42. if action != nil {
  43. button.addTarget(target, action: action!, for: .touchUpInside)
  44. }
  45. button.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
  46. // if button.bounds.width < 40 || button.bounds.height > 40 {
  47. // let width = 40 / button.bounds.height * button.bounds.width;
  48. // button.bounds = CGRect(x: 0, y: 0, width: width, height: 40)
  49. // }
  50. self.init(customView: button)
  51. }
  52. }