SwiftとCocoa

clockBargraph2

全てをSwiftで書こうとしているところです。

//  MyView.swift

import Cocoa

class MyView: NSView {
    
    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
        
        NSColor.brownColor().set()
        NSRectFill(self.bounds)
        
        let font = NSFont.boldSystemFontOfSize(70)
        let textFontAttributes = [
            NSFontAttributeName: font,
            NSForegroundColorAttributeName: NSColor.whiteColor()
        ]
        
        let now = NSDate()
        let df = NSDateFormatter()
        df.dateFormat = "HH:mm:ss"
        var s = df.stringFromDate(now)
        s.drawInRect(self.bounds, withAttributes: textFontAttributes)
        
        let hhmmss: [String] = ["hh", "mm", "ss"]
        
        for (var j: Int = 0; j<3; j++) {
            
            df.dateFormat = hhmmss[j]
            s = df.stringFromDate(now)
            switch j {
            case 0: NSColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0).set()
            case 1: NSColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0).set()
            case 2: NSColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0).set()
            default: break
            }
            for (var i: Int = 0; i<Int(s); i++) {
                let x = CGFloat(  20 + 10*i )
                let y = CGFloat( 150 + i%10 - j*50)
                let rect = NSMakeRect(x, y, 7, 40)
                NSRectFill(rect)
            }
            
        }
    }
}
//  AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var myCustomView: NSView!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        
        self.window.delegate = self
        NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "update", userInfo: nil, repeats: true)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    func update() {
        myCustomView.display()
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.