KMNCustomAlertView.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // KMNCustomAlertView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by 丁林圭 on 2024/10/14.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. class KMNCustomAlertView: NSView {
  10. override func draw(_ dirtyRect: NSRect) {
  11. super.draw(dirtyRect)
  12. }
  13. static func alertView(message: String, type: ComponentMessageType, fromView supverView: NSView, point:NSPoint) -> ComponentMessage? {
  14. let properties: ComponentMessageProperty = ComponentMessageProperty(messageType: type, title: message)
  15. let componentMessage = ComponentMessage()
  16. componentMessage.properties = properties
  17. let style = NSMutableParagraphStyle()
  18. style.lineBreakMode = .byWordWrapping
  19. style.alignment = .center
  20. let font = componentMessage.properties.propertyInfo.textFont
  21. var offsetSize = CGSize.zero
  22. let attributes: [NSAttributedString.Key: Any] = [
  23. .font: font,
  24. .paragraphStyle: style
  25. ]
  26. let maxSize = CGSize(width: min(supverView.frame.size.width - 80, 500), height: supverView.frame.size.height - 40)
  27. let size = message.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: attributes).size
  28. let ceilSize = NSSize(width: ceil(size.width), height: ceil(size.height))
  29. offsetSize = NSSize(width: ceilSize.width + 60, height: ceilSize.height + 30)
  30. componentMessage.frame = NSRect(x: (point.x - offsetSize.width/2),
  31. y: (point.y - offsetSize.height/2),
  32. width: offsetSize.width, height: offsetSize.height)
  33. supverView.addSubview(componentMessage)
  34. componentMessage.alphaValue = 0.0
  35. NSAnimationContext.runAnimationGroup({ context in
  36. context.duration = 0.3 // 设置动画持续时间
  37. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  38. componentMessage.animator().alphaValue = 1.0 // 动画化透明度
  39. }, completionHandler: {
  40. })
  41. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  42. NSAnimationContext.runAnimationGroup({ context in
  43. context.duration = 0.3 // 设置动画持续时间
  44. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  45. componentMessage.animator().alphaValue = 0.0 // 动画化透明度
  46. }, completionHandler: {
  47. componentMessage.removeFromSuperview()
  48. })
  49. }
  50. return componentMessage
  51. }
  52. }