ヒレガス本 第4章 コントロール
RaiseManプロジェクト、やった。
- TextFieldには、フォーマッタをドロップ(アタッチ)することができる。これによって数値や日付でバリデーションが可能。へー。
- NSWindowのアウトレットに、initialFirstResponderがある。これをコントロールに接続しておくと、起動時にフォーカスがあたる。へー。
- NSViewのアウトレットに、nextKeyViewがある。これをコントロールに接続しておくと、Tabキーでの移動先を指定できる。へー。ViewからViewへ直接接続できるんだ。へー。
追記:RubyCocoaで書いてみた。nibは今回も使いまわし。
- NSString.stringWithFormatで可変長引数リストを渡そうとして、うまくいかなかった。まあそんなのを使わなくてもRubyで書けるからとりあえずOKだけど。そのうち。
- deallocメソッドが呼ばれないなあ。勝手にやってくれるのかなあ。
require 'osx/cocoa' include OSX class MyDocument < NSDocument ib_outlet :deleteButton, :nextButton, :previousButton ib_outlet :nameField, :raiseField, :box def initialize @employees = []; createNewEmployee end def nextEmployee(sender) updateEmployee @currentIndex += 1 updateUI end def previousEmployee(sender) updateEmployee @currentIndex -= 1 updateUI end def deleteEmployee(sender) @employees.delete_at(@currentIndex) if @currentIndex != 0 @currentIndex -= 1 end updateUI end def newEmployee(sender) updateEmployee createNewEmployee updateUI end def createNewEmployee @employees.push Person.alloc.init @currentIndex = @employees.size - 1 end def updateEmployee e = @employees[@currentIndex] e.setPersonName @nameField.stringValue e.setExpectedRaise @raiseField.floatValue end def updateUI r = "Record %d of %d" % [@currentIndex + 1, @employees.size] e = @employees[@currentIndex] @nameField.setStringValue e.personName @raiseField.setFloatValue e.expectedRaise @box.setTitle r @previousButton.setEnabled(@currentIndex > 0) @nextButton.setEnabled(@currentIndex < @employees.size - 1) @deleteButton.setEnabled(@employees.size > 1) end ns_overrides 'windowNibName', 'windowControllerDidLoadNib:', 'dataRepresentationOfType:', 'loadDataRepresentation:ofType:' def windowNibName return "MyDocument" end def windowControllerDidLoadNib (aController) super_windowControllerDidLoadNib(aController) updateUI end def dataRepresentationOfType (aType) return nil end def loadDataRepresentation_ofType (data, aType) return true end def dealloc super end end class Person < NSObject def initialize setPersonName "NewEmployee" setExpectedRaise 0.0 end def personName @person_name end def setPersonName(person_name) @person_name = person_name end def expectedRaise @expected_raise end def setExpectedRaise(expected_raise) @expected_raise = expected_raise end def dealloc NSLog("Dealocing %@", @person_name) super end end
最後の練習問題は、また今度。
追記:演習問題。nibは省略。
require 'osx/cocoa' include OSX class CountLetter < NSObject ib_outlet :count, :text def update @count.setIntValue(@text.stringValue.length) end end