BFUIButton+ext.swift 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // UIButton+ext.swift
  3. // PQSpeed
  4. //
  5. // Created by ak on 2020/8/14.
  6. // Copyright © 2020 BytesFlow. All rights reserved.
  7. //
  8. /**
  9. UIButton图像文字同时存在时---图像相对于文字的位置
  10. - top: 图像在上
  11. - left: 图像在左
  12. - right: 图像在右
  13. - bottom: 图像在下
  14. */
  15. public enum PQButtonImageEdgeInsetsStyle {
  16. case top, left, right, bottom
  17. }
  18. import Foundation
  19. public extension UIButton {
  20. func imagePosition(at style: PQButtonImageEdgeInsetsStyle, space: CGFloat) {
  21. guard let imageV = imageView else { return }
  22. guard let titleL = titleLabel else { return }
  23. // 获取图像的宽和高
  24. let imageWidth = imageV.frame.size.width
  25. let imageHeight = imageV.frame.size.height
  26. // 获取文字的宽和高
  27. let labelWidth = titleL.frame.size.width
  28. let labelHeight = titleL.frame.size.height
  29. var imageEdgeInsets = UIEdgeInsets.zero
  30. var labelEdgeInsets = UIEdgeInsets.zero
  31. // UIButton同时有图像和文字的正常状态---左图像右文字,间距为0
  32. switch style {
  33. case .left:
  34. // 正常状态--只不过加了个间距
  35. imageEdgeInsets = UIEdgeInsets(top: 0, left: -space * 0.5, bottom: 0, right: space * 0.5)
  36. labelEdgeInsets = UIEdgeInsets(top: 0, left: space * 0.5, bottom: 0, right: -space * 0.5)
  37. case .right:
  38. // 切换位置--左文字右图像
  39. // 图像:UIEdgeInsets的left是相对于UIButton的左边移动了labelWidth + space * 0.5,right相对于label的左边移动了-labelWidth - space * 0.5
  40. imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth + space * 0.5, bottom: 0, right: -labelWidth - space * 0.5)
  41. labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth - space * 0.5, bottom: 0, right: imageWidth + space * 0.5)
  42. case .top:
  43. // 切换位置--上图像下文字
  44. /** 图像的中心位置向右移动了labelWidth * 0.5,向上移动了-imageHeight * 0.5 - space * 0.5
  45. *文字的中心位置向左移动了imageWidth * 0.5,向下移动了labelHeight*0.5+space*0.5
  46. */
  47. imageEdgeInsets = UIEdgeInsets(top: -(imageHeight * 0.5 - space), left: labelWidth * 0.5, bottom: imageHeight * 0.5 - space, right: -labelWidth * 0.5)
  48. labelEdgeInsets = UIEdgeInsets(top: labelHeight * 0.5 + space * 2, left: -imageWidth * 0.5, bottom: -(labelHeight * 0.5 + space * 2), right: imageWidth * 0.5)
  49. case .bottom:
  50. // 切换位置--下图像上文字
  51. /** 图像的中心位置向右移动了labelWidth * 0.5,向下移动了imageHeight * 0.5 + space * 0.5
  52. *文字的中心位置向左移动了imageWidth * 0.5,向上移动了labelHeight*0.5+space*0.5
  53. */
  54. imageEdgeInsets = UIEdgeInsets(top: imageHeight * 0.5 + space * 0.5, left: labelWidth * 0.5, bottom: -imageHeight * 0.5 - space * 0.5, right: -labelWidth * 0.5)
  55. labelEdgeInsets = UIEdgeInsets(top: -labelHeight * 0.5 - space * 0.5, left: -imageWidth * 0.5, bottom: labelHeight * 0.5 + space * 0.5, right: imageWidth * 0.5)
  56. }
  57. titleEdgeInsets = labelEdgeInsets
  58. self.imageEdgeInsets = imageEdgeInsets
  59. }
  60. }