Reputation: 2488
I am making an iOS calculator and it I'm having minor difficulties with the backspace button (for deleting the last number of the value displayed on a label).
To get the current value on the label I use
double currentValue = [screenLabel.text doubleValue]
Following other questions, I tried something like
-(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]];
}
But it does not work,
(Xcode says "setText is deprecated", "NSString may not respond to setText" and that an identifier is expected in the first line of code inside the IBAction)
and I do not really understand this code to make it work by myself.
What should I do?
Upvotes: 1
Views: 3244
Reputation: 23278
It should be
[screenLabel setText:[NSString stringWithFormat:@"%@",temp]];
Your Xcode clearly says that you are trying to call setText' method on an
NSStringwhere as you should be calling that on a
UILabel. Your
screenLabel.textis retuning an
NSString. You should just use
screenLabelalone and should call
setText` on that.
Just use,
NSString *string = [screenLabel text];
The issue with that was that, you are using [screenLabel.text];
which is not correct as per objective-c syntax to call text
method on screenLabel
. Either you should use,
NSString *string = [screenLabel text];
or
NSString *string = screenLabel.text;
In this method, I dont think you need to use NSMutableString
. You can just use NSString
instead.
In short your method can be written as,
-(IBAction)backspacePressed:(id)sender
{
NSString *string = [screenLabel text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
[screenLabel setText:temp];
}
As per your question in comments(which is deleted now), if you want to display zero when there are no strings present, try,
-(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];
}
Upvotes: 3