这个代码做的事情很简单,按键盘的“上”,文本框中的数字会增加,反之,按“下”,文本框中的数字会减少。
开始时,我们过滤掉除数字键之外不需要的按键,保留箭头按键。
if ( [theArrow length] == 0 ) {
return; // reject dead keys
}
if ( [theArrow length] == 1 ) {
// Grab just the key pressed
unichar keyChar = [theArrow characterAtIndex:0];
接着,我们获取到一个字符,代表按下的键(上箭头或者下箭头)
if ([theEvent modifierFlags] & NSNumericPadKeyMask) {
NSString *theArrow = [theEvent charactersIgnoringModifiers];
下面的内容处理“上”箭头和“下”箭头的按键。
// If it was an up arrow key
if ( keyChar == NSUpArrowFunctionKey ) {
// Setup the loop, wrapping action between bounds
if ( [[self stringValue] doubleValue] < [stepper maxValue] ) {
NSNumber *value = [NSNumber numberWithInt:[[self stringValue] intValue] + 1];
[self setStringValue:[value stringValue]];
} else if ( [[self stringValue] doubleValue] >= [stepper maxValue] ) {
[self setStringValue:@"1"];
}
}
// if it was a down arrow key
else if ( keyChar == NSDownArrowFunctionKey ) {
// Setup loop, wrapping action between bounds
if ( [[self stringValue] doubleValue] > 1 ) {
NSNumber *value = [NSNumber numberWithInt:[[self stringValue] intValue] - 1];
[self setStringValue:[value stringValue]];
} else if ( [[self stringValue] doubleValue] <= 1 ) {
[self setStringValue:[NSString stringWithFormat:@"%.0lf", [stepper maxValue]]];
}
}
需要注意的是我们获取keyUp:消息,这是因为keyDown:消息已经被NSTextField事先截获了。
这样,当用户按“下”箭头,输入框中的数字会减一,按“上”箭头,会加一。如果数字超过maxValue,将返回为1,如果小于1,将返回最大值(maxValue)。