我想为我的计算器应用程序实现一个删除键。我的伪代码是:
foo = length of current number
bar = length of current number-1
current number = current number with character at index (foo-bar) removed
为了在 Objective-C 中做到这一点,我尝试使用 NSRange 函数以及 StringbyappendingString 方法来实现它:
- (IBAction)DelPressed {
if ([self.display.text length] >=2)
{
int len = [self.display.text length];//Length of entire display
//Add to the brainlong printing out the length of the entire display
self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len];
int le = ([self.display.text length]-1);//Length of entire display - 1
NSString *lestring = [NSString stringWithFormat:@"LE is %g",le];
//Add to the brainlog printing out the length of the display -1
self.brainlog.text = [self.brainlog.text stringByAppendingString:lestring];
NSRange range = NSMakeRange(le, len);//range only includes the last character
self.display.text = [self.display.text stringByReplacingCharactersInRange:range withString:@" "];//Replace the last character with whitespace
}
Brainlog 的输出(即 le 和 len 的长度)是:
Len is -1.99164 Le is -1.99164
很难看,但这是我使用 iOS 模拟器输入计算器的数字的图像:
我试图更改 le 的值(即,使其显示长度为 -3 或 -5 等),并且 le 和 len 仍然相同。
我还尝试使 le 参考 len:
int len = [self.display.text length];//Length of entire display
//Add to the brainlong printing out the length of the entire display
self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len];
int le = len-1;
但是两者的价值观还是一样的。如何使用 NSRange 删除显示的最后一个字符?
编辑:使用达斯汀的修复,我现在将一个相当冗长的函数简化为 6 行代码:
-(IBAction)DelPressed{
if ([self.display.text length] >=2)
{
self.display.text = [self.display.text substringToIndes:[self.display.text length] -1];
}
}