LoginSignup
10
6

More than 5 years have passed since last update.

NSViewとNSViewController【swiftでmacOSのアプリ開発、情報が少ないから少しずつでも書いていこうと思う】

Posted at

どこで見たかは忘れてしまったけど、NSbutton のデザインを変更するのは
あまりオススメしないからNSViewを使ったほうがいい。
っていうのを見た記憶があるので、それに従おうと頑張ってます。(鵜呑みにしていいものか...)

以下のようなNSViewのクラスを作り、

NavButton.swift
class NavButton: NSView {

    private var color: NSColor?
    private var text: String?

    init(frame frameRect: NSRect, str: String, color: NSColor) {
        super.init(frame: frameRect)

        self.text = str
        self.color = color
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func draw(_ dirtyRect: NSRect) {
        self.color!.setFill()
        NSRectFill(self.bounds)

        NSString(string: self.text!).draw(in: self.bounds, withAttributes: nil)
    }

    override func mouseDown(with event: NSEvent) {
        if event.clickCount == 2 {
            Swift.print("double clicked")
        }
        else {
            super.mouseDown(with: event)
            Swift.print("clicked")
        }
    }
}

NSViewControllerで次のようにViewに描写してみる

ViewController.swift
class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let item = NavButton(frame: NSMakeRect(0, 0, 200, 50), str: "test", color: NSColor.blue)

        self.view.addSubview(item)
    }

すると、こんな感じに表示される。
sample.png

10
6
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
10
6