0

Here is my entire sheet, I'm kinda lost so. My action btnResult is working just fine and getting the result i want. But i need to execute the action if the user only typed in numbers else they should get an error message.

can you finish the sheet, so i can see what you mean?

    - (IBAction)btnResult:(id)sender
    {
        float sum = (_tf1.floatValue * (_tf3.floatValue + 1) - (_tf2.floatValue * _tf3.floatValue));

        float divideOne = sum/3;
        float divideTwo = sum/3*2;


        float value1 = divideOne;
        int intValue1 = (int)value1;
        float fractional1 = fmodf(value1, (float)intValue1);

        if(fractional1 > .5f)
            intValue1++;


        float value2 = divideTwo;
        int intValue2= (int)value2;
        float fractional2 = fmodf(value2, (float)intValue2);

        if(fractional2 > .5f)
            intValue2++;


        _lblResult.floatValue = intValue1;
        _lblResult2.floatValue = intValue2;

        _lblAbove.hidden = NO;
        _lblBelow.hidden = NO;

        _lblResult.hidden = NO;
        _lblResult2.hidden = NO;
    }
Beltalowda
  • 4,300
  • 2
  • 22
  • 33
Giefdonut
  • 89
  • 1
  • 2
  • 9

2 Answers2

2

This is not the way to proceed to get this done you can make use of the textfield delegate methods for this purpose use

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Check the string and using regular expression return weather to accept or reject a value entered in this method

See this answer for the working example

Community
  • 1
  • 1
Lithu T.V
  • 19,491
  • 11
  • 53
  • 98
  • I have found the same answer many places but i fail to understand and implement them. Can you make an 'working' example, so i can see it work? – Giefdonut Nov 29 '13 at 09:09
0

You need to set the Delegate of the UITextField to self and implement the following delegate method:

-(BOOL)isNumeric:(NSString*)inputString
{
    NSCharacterSet *cs=[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString *filtered;
    filtered = [[inputString componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [inputString isEqualToString:filtered];
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    // Check for non-numeric characters
    return [self isNumeric:textField.text];
}

Enjoy :)

Vinay Jain
  • 2,601
  • 3
  • 24
  • 42