SNV7
SNV7

Reputation: 2593

UIKeyboardTypeDecimalPad with negative numbers

I'm working on an iOS app that requires the user to enter numbers into a UITextField using the keyboard type UIKeyboardTypeDecimalPad. However I just realized that there is no support for entering negative numbers, which is a requirement of the application.

Any ideas or thoughts on how I can accomplish this?

Upvotes: 7

Views: 6320

Answers (6)

Leszek Szary
Leszek Szary

Reputation: 10346

func addToolbar() {
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    let plusMinusButton = UIBarButtonItem(title: "+/-", style: .done, target: self, action: #selector(plusMinusAction))
    plusMinusButton.tintColor = .black
    plusMinusButton.width = UIScreen.main.bounds.width / 3
    toolbar.items = [plusMinusButton]
    toolbar.barTintColor = #colorLiteral(red: 0.7812563181, green: 0.8036255836, blue: 0.8297665119, alpha: 1)
    toolbar.isTranslucent = false
    myField.inputAccessoryView = toolbar
}

@objc func plusMinusAction() {
    let text = myField.text ?? ""
    if text.hasPrefix("-") {
        myField.text = String(text.suffix(text.count - 1))
    } else {
        myField.text = "-\(text)"
    }
}

Upvotes: 2

danihvilla
danihvilla

Reputation: 31

To accomplish the task I came using '.inputAccessoryView' with the textfield

On viewDidLoad

self.textField.inputAccessoryView = [self accessoryViewForTextField:self.textField];

then

- (UIView *)accessoryViewForTextField:(UITextField *)textField{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
view.backgroundColor = [UIColor lightGrayColor];

UIButton *minusButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
[minusButton setTitle:@"-" forState:UIControlStateNormal];
[doneButton setTitle:NSLocalizedString(@"Done", @"Done") forState:UIControlStateNormal];
minusButton.backgroundColor = [UIColor magentaColor];
doneButton.backgroundColor = [UIColor blueColor];
CGFloat buttonWidth = view.frame.size.width/3;
minusButton.frame = CGRectMake(0, 0, buttonWidth, 44);
doneButton.frame = CGRectMake(view.frame.size.width - buttonWidth, 0, buttonWidth, 44);

[minusButton addTarget:self action:@selector(minusTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
[doneButton addTarget:self action:@selector(doneTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];

[view addSubview:minusButton];
[view addSubview:doneButton];

return view;

}

this will add a custom view just above the keyboard as a part of it

finally to get the 'minus'

#pragma mark - IBActions

- (IBAction)minusTouchUpInside:(id)sender
{
NSString *value = self.textField.text;
if (value.length > 0) {
    NSString *firstCharacter = [value substringToIndex:1];
    if ([firstCharacter isEqualToString:@"-"]){
        self.textField.text = [value substringFromIndex:1];
    }else{
        self.textField.text = [NSString stringWithFormat:@"-%@", value];
    }
}
}

- (IBAction)doneTouchUpInside:(id)sender
{
    [self.textField resignFirstResponder];
}

Upvotes: 0

user1687195
user1687195

Reputation: 9196

You can use a UIToolbar as an input accessory view for your UITextField and put a button with a "+/-" (plus/minus sign in it).

UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
UIBarButtonItem *plusMinusBbi = [[UIBarButtonItem alloc]initWithTitle:@"+/-" style:UIBarButtonItemStylePlain target:self action:@selector(togglePositiveNegative:)];
toolbar.items = @[plusMinusBbi];
self.textField.inputAccessoryView = toolbar;

Upvotes: 4

Floris497
Floris497

Reputation: 1406

This clearly isn't my best answer.. but i'm unable to delete it since it is accepted.

may this code will help you:

if you want a negative number just use "-"

NSString *fieldString = [NSString stringWithFormat:@"%@",Textfield.text];

        NSLog(@"%@",fString);

        int fieldValue;
        value = [fString intValue];
        NSLog(@"%d",fieldValue);

this will work for decimal numbers

            double fieldValue;
            value = [fString doubleValue];
            NSLog(@"%f",fieldValue);

Upvotes: 0

anders
anders

Reputation: 4218

From what I've found apple has yet to implement such a standard keyboard. However it is possible to add UIButtons to any keyboard window. this link should help, or similar tutorial this link should also help

Basically you register a NSNotificationListener to listen for the keyboard coming up. Grab the keyboards frame and add a UIButton to its view. The above link isn't quite what we want but its the right idea.

In appDelegate,

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

    - (void)keyboardDidShow:(NSNotification *)note
    {
// Get the Very Top Window on the Display. That's where the Keyboard is.
NSInteger topWindow = [[[UIApplication sharedApplication] windows] count] - 1;
UIWindow *keyboard = [[[UIApplication sharedApplication] windows] objectAtIndex:topWindow];
// If the dot has not been created (first time the keyboard has been displayed) create it.
if (self.dot == nil)
    {
    self.dot = [UIButton buttonWithType:UIButtonTypeCustom];
    // Make the dot a subview of the view containing the keyboard.
    [keyboard addSubview:self.dot];
    // Place the dot in the correct location on the keyboard.
    [self.dot setFrame:CGRectMake(0, 427, 106, 53)];
    // Set the overlay graphics. (Use TransDecimalDown.png and TransDecimalUp.png for the Alert Style Keyboard.
    [self.dot setImage:[UIImage imageNamed:@"DecimalUp.png"] forState:UIControlStateNormal];
    [self.dot setImage:[UIImage imageNamed:@"DecimalDown.png"] forState:UIControlStateHighlighted];
    // Give the dot something to do when pressed.
    [self.dot addTarget:self action:@selector(sendDecimal:)  forControlEvents:UIControlEventTouchUpInside];
}
// Bring the dot to the front of the keyboard.
[keyboard bringSubviewToFront:self.dot];
    }

    - (void)sendDecimal:(id)sender {
// Post a notification that the dot has been pressed. Observing view controllers are then responsible for adding the actual decimal.
[[NSNotificationCenter defaultCenter] postNotificationName:@"DecimalPressed" object:nil];
// Play the Keyboard Click. If the user has these sound effects turned off, the decimal will still click. Sorry.  :(  (Also, doesn't seem to work on the simulator, no keyboard clicks seem to.)
AudioServicesPlaySystemSound(0x450);
    }

sorry for the horrible code format but you get the idea :)

Upvotes: 1

Pedro Góes
Pedro Góes

Reputation: 747

I don't believe that something like that is possible right now (since Apple hasn't implemented it yet). The only option would be to design your own keyboard or use a complete ASCII one.

Upvotes: 2

Related Questions