【问题标题】:Making a backspace button for a calculator为计算器制作退格按钮
【发布时间】:2012-11-14 06:32:39
【问题描述】:

我正在制作一个 iOS 计算器,但我在使用退格按钮时遇到了一些小问题(用于删除标签上显示的值的最后一个数字)。

要获取我使用的标签上的当前值

    double currentValue = [screenLabel.text doubleValue]

在其他问题之后,我尝试了类似

-(IBAction)backspacePressed:(id)sender
{
NSMutableString *string = (NSMutableString*)[screenLabel.text];

int length = [string length];

NSString *temp = [string substringToIndex:length-1]
;

[screenLabel.text setText:[NSString stringWithFormat:@"%@",temp]];

}

但它不起作用,

(Xcode 说“setText is deprecated”,“NSString may not respond to setText”并且第一个需要一个标识符 IBAction 内的代码行)

而且我并不真正理解这段代码以使其自己工作。

我该怎么办?

【问题讨论】:

    标签: objective-c ios xcode calculator


    【解决方案1】:

    应该是

    [screenLabel setText:[NSString stringWithFormat:@"%@",temp]];
    

    您的 Xcode 清楚地表明您正在尝试调用 setText' method on anNSStringwhere as you should be calling that on aUILabel. YourscreenLabel.textis retuning anNSString. You should just usescreenLabelalone and should callsetText`。

    随便用,

    NSString *string = [screenLabel text];
    

    问题在于,您使用的是 [screenLabel.text];,根据 Objective-c 语法在 screenLabel 上调用 text 方法是不正确的。要么你应该使用,

    NSString *string = [screenLabel text];
    

    NSString *string = screenLabel.text;
    

    在这个方法中,我认为你不需要使用NSMutableString。你可以改用NSString

    简而言之,你的方法可以写成,

    -(IBAction)backspacePressed:(id)sender
    {
       NSString *string = [screenLabel text];
       int length = [string length];
       NSString *temp = [string substringToIndex:length-1];
       [screenLabel setText:temp];
    }
    

    根据您在 cmets 中的问题(现在已删除),如果您想在没有字符串时显示零,请尝试,

    -(IBAction)backspacePressed:(id)sender
    {
       NSString *string = [screenLabel text];
       int length = [string length];
       NSString *temp = [string substringToIndex:length-1];
    
       if ([temp length] == 0) {
         temp = @"0";
       }
       [screenLabel setText:temp];
    }
    

    【讨论】:

    • 或者跳过 setText 方法直接使用:"screenLabel.text = temp;"?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多