TSCustomAlertController.swift 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // TSCustomAlertController.swift
  3. // Pods
  4. //
  5. // Created by 100Years on 2025/3/26.
  6. //
  7. import UIKit
  8. public class TSCustomAlertController {
  9. // MARK: - 配置模型
  10. public struct AlertConfig {
  11. public var style: UIUserInterfaceStyle = .light
  12. public var message: String
  13. public var messageColor: UIColor = .white
  14. public var messageFont: UIFont = .systemFont(ofSize: 16)
  15. public var cancelTitle: String = "Retain".localized
  16. public var cancelColor: UIColor = .white
  17. public var confirmTitle: String = "Delete".localized
  18. public var confirmColor: UIColor = UIColor.themeColor
  19. public var cancelAction: (() -> Void)?
  20. public var confirmAction: (() -> Void)?
  21. public init(style:UIUserInterfaceStyle = .dark,
  22. message: String,
  23. messageColor: UIColor = .white,
  24. messageFont: UIFont = .systemFont(ofSize: 16),
  25. cancelTitle: String = "Retain".localized,
  26. cancelColor: UIColor = .white,
  27. confirmTitle: String = "Delete".localized,
  28. confirmColor: UIColor = UIColor.themeColor,
  29. cancelAction: ( () -> Void)? = nil,
  30. confirmAction: ( () -> Void)? = nil) {
  31. self.style = style
  32. self.message = message
  33. self.messageColor = messageColor
  34. self.messageFont = messageFont
  35. self.cancelTitle = cancelTitle
  36. self.cancelColor = cancelColor
  37. self.confirmTitle = confirmTitle
  38. self.confirmColor = confirmColor
  39. self.cancelAction = cancelAction
  40. self.confirmAction = confirmAction
  41. }
  42. }
  43. // MARK: - 显示弹窗
  44. public static func show(in viewController: UIViewController, config: AlertConfig) {
  45. // 1. 创建AlertController (title设为空字符串而不是nil,避免自动上移)
  46. let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
  47. // 2. 自定义message
  48. let messageAttributed = NSAttributedString(
  49. string: config.message,
  50. attributes: [
  51. .foregroundColor: config.messageColor,
  52. .font: config.messageFont
  53. ]
  54. )
  55. alert.setValue(messageAttributed, forKey: "attributedMessage")
  56. // 设置黑暗模式
  57. alert.overrideUserInterfaceStyle = config.style
  58. // 3. 添加取消按钮
  59. let cancelAction = UIAlertAction(title: config.cancelTitle, style: .default) { _ in
  60. config.cancelAction?()
  61. }
  62. cancelAction.setValue(config.cancelColor, forKey: "titleTextColor")
  63. alert.addAction(cancelAction)
  64. // 4. 添加确定按钮
  65. let confirmAction = UIAlertAction(title: config.confirmTitle, style: .default) { _ in
  66. config.confirmAction?()
  67. }
  68. confirmAction.setValue(config.confirmColor, forKey: "titleTextColor")
  69. alert.addAction(confirmAction)
  70. // 5. 显示弹窗
  71. viewController.present(alert, animated: true)
  72. }
  73. }