Search code examples
objective-cnsstringlabelnsslider

Add "%" to a constantly changing string


I have a NSSlider and an NSLabel. When the slider's value changes it changes the label's text to the new value. My problem is that I want to a "%" at the end, but whenever I try to change my code, error occurs.

Here's my code:

int sliderValue = [_opacSlider intValue];
NSString *stringValue = [NSString stringWithFormat:@"%i",sliderValue];
[_opacLabel setStringValue:stringValue];

What I attempted doing was this:

[_opacLabel setStringValue:(stringValue, @"%")];

But then the label doesn't change and remains "%".

Any ideas why this is not working and what I should change?


Solution

  • Since stringWithFormat: method interprets % as a special character, you need to use %% to print a single %:

    int sliderValue = [_opacSlider intValue];
    NSString *stringValue = [NSString stringWithFormat:@"%i%%",sliderValue];
    //                                                     ^^
    [_opacLabel setStringValue:stringValue];