Swift实现前缀功能

  1. 需要先定义一个 泛型结构体;用来存储传入的值
  2. 定义RouterCompatible接口,并给这个接口扩展默认实现,使不论是类还是对象,只要遵守了这个接口,那么都能够获取到Router示例
  3. 在给任何类添加前缀的时候,只需要遵守这个接口,拓展自己想要实现的逻辑即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

struct Router<T> {
var base: T
init(_ base:T) {
self.base = base
}
}

protocol RouterCompatible {}

extension RouterCompatible {
var router: Router<Self> {
get { Router(self) }
set {} /* 规定: 必须写*/
}
static var router:Router<Self>.Type {
get {Router<Self>.self}
set {}
}
}

假设给NSViewController 添加Route 功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
enum RouterType {
case normal // via windowCtl
case modalWindow
case sheet
}
extension NSViewController: RouterCompatible {}

//extension Router where T == NSViewController { //不要约定死,否则其子类不能调用
extension Router where T: NSViewController {
func show(ctrl: NSViewController, type routerType: RouterType = .normal){
switch routerType {
case .normal:
let vc = ctrl
let window = NSWindow(contentViewController: vc)
window.styleMask = [.titled, .closable, .resizable]
window.setContentSize(.init(width: Helper.ui.app_width, height: Helper.ui.app_height))
// window.setFrame(.init(x: 0, y: 0, width: Helper.ui.app_width, height: Helper.ui.app_height), display: true)
// window.title = title
let windowCtl = NSWindowController(window: window)
windowCtl.showWindow(self.base)
case .modalWindow:
// ctrl.title = "DDDD"
self.base.presentAsModalWindow(ctrl)
case .sheet:
self.base.presentAsSheet(ctrl)
}
}
}

使用流程如下: 在ViewController 中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@IBAction func ctl_transfrom(_ sender: Any) {
let btn = sender as! NSButton

let tag = btn.tag

switch tag {
case 0:
let vc = NormalCtl()
vc.title = "Normal Ctl"
self.router.show(ctrl: vc)

case 1:

let vc = ModalCtl()
vc.title = "Modal Ctl 1"
self.router.show(ctrl: vc, type: .modalWindow)

case 2:
let vc = ModalCtl()
vc.title = "Modal Ctl 2"
self.router.show(ctrl: vc, type: .sheet)

case 3:

let vc = TableViewCtl()
vc.title = "TableViewCtl"
self.router.show(ctrl: vc)
default:
break
}
}

Swift实现前缀功能
https://jackiedai.github.io/2024/12/25/015MacOS/002_Swift_Prefix/
Author
lingXiao
Posted on
December 25, 2024
Licensed under