LNViewController.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // LNViewController.swift
  3. // Lanu
  4. //
  5. // Created by OneeChan on 2025/11/6.
  6. //
  7. import Foundation
  8. import UIKit
  9. class LNViewController: UIViewController {
  10. var showNavigationBar = true
  11. var enableDragBack = true
  12. var navigationBarColor: UIColor = .white
  13. var customBack: (() -> Void)?
  14. override func viewDidLoad() {
  15. super.viewDidLoad()
  16. view.backgroundColor = .white
  17. edgesForExtendedLayout = []
  18. // hidesBottomBarWhenPushed = true
  19. let button = UIButton(type: .system)
  20. let buttonImage: UIImage? = .init(systemName: "chevron.backward")?.withRenderingMode(.alwaysTemplate)
  21. button.contentHorizontalAlignment = .center
  22. button.setImage(buttonImage, for: .normal)
  23. button.tintColor = .black
  24. button.addAction(UIAction(handler: { [weak self] _ in
  25. guard let self else { return }
  26. if let customBack {
  27. customBack()
  28. } else {
  29. navigationController?.popViewController(animated: true)
  30. }
  31. }), for: .touchUpInside)
  32. navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
  33. }
  34. func setRightButton(_ view: UIView?) {
  35. if let view {
  36. navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
  37. } else {
  38. navigationItem.rightBarButtonItem = nil
  39. }
  40. }
  41. override func viewWillAppear(_ animated: Bool) {
  42. super.viewWillAppear(animated)
  43. navigationController?.setNavigationBarHidden(!showNavigationBar, animated: animated)
  44. if showNavigationBar,
  45. let navBar = navigationController?.navigationBar {
  46. // 1. 配置外观(iOS 15+ 必须用 UINavigationBarAppearance)
  47. let appearance = UINavigationBarAppearance()
  48. appearance.backgroundColor = navigationBarColor // 导航栏背景色
  49. appearance.shadowColor = .clear // 去除底部阴影线
  50. if navigationBarColor == .clear {
  51. appearance.configureWithTransparentBackground()
  52. }
  53. // 2. 应用外观设置(iOS 15+ 需要设置 scrollEdgeAppearance 和 standardAppearance)
  54. navBar.scrollEdgeAppearance = appearance // 滚动到顶部时的外观(如列表顶部)
  55. navBar.standardAppearance = appearance // 常规状态的外观
  56. navBar.compactAppearance = appearance
  57. }
  58. }
  59. }