我正在制作一个具有罗马数字模式的计算器。我在模型视图和视图控制器中执行了操作。我的问题是我需要将罗马数字转换为 NSNumber。有一个 UILabel,视图控制器获取标签中的内容并将其设置为模型视图的操作数。有谁知道我如何从标签中取出罗马数字并将其设为 NSNumber?这是一些代码:
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [[sender titleLabel] text];
if (self.userIsTypingNumber) {
[self.display setText:[self.display.text stringByAppendingString:digit]];
} else {
[self.display setText:digit];
self.userIsTypingNumber = YES;
}
}
- (IBAction)operationPressed:(UIButton *)sender {
if (self.userIsTypingNumber) {
if ([self isValidForRoman:self.display.text] == YES) {
//find out what roman numeral is in the display
} else {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
NSNumber *n = [numberFormatter numberFromString:self.display.text];
[[Model singleton] setOperand:n];
self.userIsTypingNumber = NO;
}
}
NSString *operation = [[sender titleLabel] text];
NSNumber *result = [[Model singleton] performOperation:operation];
[self.display setText:[NSString stringWithFormat:@"%@", result]];
}
- (IBAction)clearDigitPressed:(UIButton *)sender {
[self.display setText:@""];
}
- (IBAction)clearOperationPressed:(UIButton *)sender {
[[Model singleton] performOperation:nil];
[self.display setText:@""];
}
- (IBAction)changeNumeralType:(id)sender {
switch ([sender selectedSegmentIndex]) {
case 0:
{
[self.button1 setTitle:@"1" forState:UIControlStateNormal];
[self.button2 setTitle:@"2" forState:UIControlStateNormal];
[self.button3 setTitle:@"3" forState:UIControlStateNormal];
[self.button4 setTitle:@"4" forState:UIControlStateNormal];
[self.button5 setTitle:@"5" forState:UIControlStateNormal];
[self.button6 setTitle:@"6" forState:UIControlStateNormal];
[self.button7 setTitle:@"7" forState:UIControlStateNormal];
[self.button8 setTitle:@"8" forState:UIControlStateNormal];
[self.button9 setTitle:@"9" forState:UIControlStateNormal];
[self.button0 setTitle:@"0" forState:UIControlStateNormal];
} break;
case 1:
{
[self.button1 setTitle:@"L" forState:UIControlStateNormal];
[self.button2 setTitle:@"C" forState:UIControlStateNormal];
[self.button3 setTitle:@"D" forState:UIControlStateNormal];
[self.button4 setTitle:@"I" forState:UIControlStateNormal];
[self.button5 setTitle:@"V" forState:UIControlStateNormal];
[self.button6 setTitle:@"X" forState:UIControlStateNormal];
[self.button7 setTitle:@"" forState:UIControlStateNormal];
[self.button8 setTitle:@"" forState:UIControlStateNormal];
[self.button9 setTitle:@"" forState:UIControlStateNormal];
[self.button0 setTitle:@"M" forState:UIControlStateNormal];
} break;
}
}
- (BOOL)isValidForRoman:(NSString *)text
{
NSString *romanRegex = @"^(?=.)(?i)M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$";
NSPredicate *romanTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", romanRegex];
return ([romanTest evaluateWithObject:text]);
}