Objective-C - Adding Characters to Certain Parts of a String

I made a quadratic equation solver for the iPhone, and when I click on the text box my own keyboard appears. I have a button that changes whether a number is positive or negative. Right now, when the button is pressed (0 is the current value of the text), this is what is displayed in the text field, so if the number is positive, it will become negative, and if it is negative, it will become positive. I'm having some problems, so I would like to put a minus sign at the beginning of the line if the number is positive, and if the number is negative, the minus sign will be removed. Can someone give me a guide on this?

+3
source share
3 answers

Instead of denying the use of a math function, I assigned an NSMutableString to my UITextField, after which I inserted the β€œ-” sign using insertString: atIndex: after that I reassigned the modified line to my UITextField. To switch between positive and negative, I created an if function, so if the float value of my text field is greater than or equal to 0, then a β€œ-” is added, but if the float value of my text field is less than zero, it is β€œdeleted using deleteCharactersInRange. Here is my code in its current form:

- (IBAction)positivity{

    NSMutableString *a = [NSMutableString stringWithString:aVal.text];


    if([aVal.text floatValue]>=0){      
    [a insertString: @"-" atIndex: 0];
    aVal.text = a;
    }
    else if([aVal.text floatValue]<0){
        NSRange range = {0,1};
        [a deleteCharactersInRange:range];
        aVal.text = a;
}

}

aVal is the name of the UITextField that I am changing.

+3
source

, - . , , . (, @Ken .)

, , , ( -1 0, ) , strong > ( ).

Cocoa ( NSControl, NSTextField), -[NSControl setIntegerValue:] . () , . ( - , -setDoubleValue: -setFloatValue:.)

, "-", . %ld %d (, @Peter!) NSInteger, 32 , :

NSString *result = [NSString stringWithFormat:@"%ld", nsIntegerValue];

, ( , ), NSMutableString -appendString: -insertString:atIndex:.

+2

. iPhone, NSMutableArray NSStrings. , "x", "^", "sin (" ..

When I needed to deny the equation, it was much easier to tell the insertObject: @ "-" atIndex: 0 array to try to insert it directly into the string. Then, whenever the array was changed, I just redid the equation line as follows:

NSString * newEquation = [equationElements componentsJoinedByString:@""];
+2
source

Source: https://habr.com/ru/post/1711873/


All Articles