LoginSignup
0
0

More than 5 years have passed since last update.

SwiftとIBAction

Posted at

先日ごくごく小さなツールを書いたときに自分でも面白いなぁと思ったので書き記しておく。

SwiftでIBAction作りにくい

作りにくいというか、NSObjectから継承する必要があって「気持ち悪い」ことがある。

JavaのActionListenerぽいやつ

JavaのActionListenerぽいのを考えたけどあまりうまくなかった

委譲しちゃえ

委譲しちゃう

ActionListener

名前だけはJavaからいただいた。

class ActionListener: NSObject {
    weak var owner: Any?
}

これだけ。

使う人

extension ActionListener {
    @IBAction func quit(_ sender: Any?) {
        NSApplication.shared().terminate(nil)
    }
}

extension Selector {
    static let quit = #selector(ActionListener.quit(_:))
}

struct QuitItem {
    let menuItem = NSMenuItem()
    private let listener = ActionListener()

    init() {
         let format = NSLocalizedString("Quit %@", comment: "Quit Menu Item")
         menuItem.title = String(format: format, AppDelegate.appName)
         menuItem.action = .quit
         menuItem.target = listener
     }
}

...委譲ではない?

既知の問題点

ぽ、ぽりもーふぃずむ???

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0