前へ Xcc>Cocoa 次へ

ということで、まずは NSButton を調べる。Webブラウザの要領でクリックすれば NSButton が表示されるざんす。 NSButton にも見つからず NSControl でようやく見つかる。


こんな感じで書かれています。

- (int)intValue

これが MyPopUpButton.h に書き込むべき文章。 setIntValue もありますな。

- (void)setIntValue:(int)anInt

というわけで、さっそく MyPopUpButton.h に書き込み〜

@interface MyPopUpButton : NSPopUpButton
{
}
- (int)intValue;
- (void)setIntValue:(int)anInt;
@end

intValue も setIntValue も最後に";"がついてるけど、これは決まり。

MyPopUpButton.mも同様に

- (int)intValue
{
}- (void)setIntValue:(int)anInt
{
}

こっちは";"のかわりに{}です。で、この{}の中に新しい処理を書いていくことになる。

- (int)intValue

-

 インスタンス用 APIかクラス用 API を識別するのに用いられる。

(int)

 このAPIはint型を返しますという意味。

int型

 自然数。小数点はあらわせない。

- (void) setIntValue: (int) anInt

(void)

 このAPIはなにも返しませんという意味。

(int)anInt

 この API は追加情報として int 型の値が必要ですという意味。

";"がついてる

 セミコロンと呼ぶ。ひとつの命令が終わったよいう合図。

ここでMyPopUpButtonでやりたいことを整理すると

intValue

  • 選択されている項目の文字列を得る。
  • 文字列から数字を得る。
  • この数字を返値として返す。

setIntValue

  • 渡された数字を元に文字列を作る。
  • この文字列に一番近いメニュー項目を選ぶ

というとになる。これにもとづいて、さっきの辞書で NSPopUpButton を調べると選択されている項目の文字列を得るには

titleOfSelectedItem

Returns the title of the item last selected by the user.

- (NSString *)titleOfSelectedItem

なんてのがあったので、これを使うことにする。

メニュー項目を選ぶには

selectItemWithTitle

Selects the item with the specified title.

- (void)selectItemWithTitle:(NSString *)title

が使えそう。で最終的に書き込まれたのがこれ。

- (int)intValue
{
return [[self titleOfSelectedItem] intValue];
}

- (void)setIntValue:(int)anInt
{
anInt = (anInt / 10) * 10;
NSString* str = [NSString stringWithFormat:@"%d", anInt];
[self selectItemWithTitle:str];
}

保存して、Xcodeに戻って実行〜。

anInt = (anInt / 10) * 10;

 数学の表記だと=は同一という意味だが、コンピュータ言語だと代入の意味になる。anIntを10で割って、10をかけた値をanIntに代入している。int型は小数点を持てないので例えばanIntが36だとすると36/10は3.6だが小数点は無視され3となる。これに10をかけるのでanIntは30となる。

 メニューが0、10、20、...、50ととびとびなので、この演算を入れている。しかし項目のない60以降はどうなるのかというと...

NSString

anInt を文字列にしている。