PQCustomSwitchView.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // PQCustomSwitchView.swift
  3. // PQSpeed
  4. //
  5. // Created by SanW on 2021/5/12.
  6. // Copyright © 2021 BytesFlow. All rights reserved.
  7. //
  8. import UIKit
  9. class PQCustomSwitchView: UIView {
  10. /// 当前选中的item
  11. var currentItemBtn: UIButton?
  12. /// 按钮点击的回调
  13. var switchChangeHandle: ((_ sender: UIButton) -> Void)?
  14. override private init(frame: CGRect) {
  15. super.init(frame: frame)
  16. }
  17. required init?(coder _: NSCoder) {
  18. fatalError("init(coder:) has not been implemented")
  19. }
  20. init(frame: CGRect, titles: [String], defaultIndex: Int = 1) {
  21. super.init(frame: frame)
  22. BFLog(message: "初始时选择的位置 is \(defaultIndex)")
  23. let itemWidth: CGFloat = frame.width / CGFloat(titles.count)
  24. for (index, itemTitle) in titles.enumerated() {
  25. let itemBtn = UIButton(type: .custom)
  26. //8 是每一个btn 的间隔
  27. itemBtn.frame = CGRect(x: CGFloat(index) * itemWidth + CGFloat(index) * 8, y: 0, width: itemWidth, height: frame.height)
  28. itemBtn.tag = index + 1
  29. itemBtn.setTitle(itemTitle, for: .normal)
  30. itemBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#959595"), for: .normal)
  31. itemBtn.setTitleColor(UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue), for: .selected)
  32. itemBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  33. itemBtn.isSelected = index == (defaultIndex - 1)
  34. if index == (defaultIndex - 1) {
  35. itemBtn.isSelected = true
  36. currentItemBtn = itemBtn
  37. itemBtn.backgroundColor = UIColor(red: 0.239, green: 0.757, blue: 0.757, alpha: 0.15)
  38. }else{
  39. itemBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#F9F9F9")
  40. }
  41. itemBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
  42. itemBtn.addCorner(corner:5)
  43. addSubview(itemBtn)
  44. }
  45. }
  46. /// 按钮点击事件
  47. /// - Parameter sender: <#sender description#>
  48. /// - Returns: <#description#>
  49. @objc func btnClick(sender: UIButton) {
  50. currentItemBtn?.isSelected = false
  51. currentItemBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 13)
  52. currentItemBtn?.backgroundColor = UIColor.hexColor(hexadecimal: "#F9F9F9")
  53. sender.isSelected = true
  54. sender.backgroundColor = UIColor(red: 0.239, green: 0.757, blue: 0.757, alpha: 0.15)
  55. // sender.backgroundColor = .red
  56. currentItemBtn = sender
  57. if switchChangeHandle != nil {
  58. switchChangeHandle!(sender)
  59. }
  60. }
  61. }