idealisticDreamer2.0 idealisticDreamer2.0 - 3 months ago 35
Swift Question

how to interact with UITextField (Swift)

I’m new in iOS dev with swift 3
I would like to display the result of calculations with UITextField so to display + - / * bottoms i have implemented a toolBar with items above number pad but i can’t interact with UITextField without an error .
I passed some hours to read and i found some solutions with action parameter but none worked.

func addDoneButtonOnNumpad(textField: UITextField) {

let keypadToolbar: UIToolbar = UIToolbar()

// add a done button to the numberpad
keypadToolbar.items=[
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: textField, action: #selector(UITextField.resignFirstResponder)),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil),

UIBarButtonItem(title: "+", style: UIBarButtonItemStyle.done, target: self, action: #selector(self.addSum(_:))),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "-", style: UIBarButtonItemStyle.done, target: textField, action: #selector(UITextField.resignFirstResponder)),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "/", style: UIBarButtonItemStyle.done, target: textField, action: #selector(UITextField.resignFirstResponder)),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "=", style: UIBarButtonItemStyle.done, target: textField, action: #selector(UITextField.resignFirstResponder))
]
keypadToolbar.sizeToFit()
// add a toolbar with a done button above the number pad
textField.inputAccessoryView = keypadToolbar
}



@IBAction func addSum(_ sender: UITextField)
{

sender.insertText("+")

}


I change my code thanks to NDoc now i find an error of uncaught exception of type NSException i dont know what is mean but i suppose like a segmentation fault maybe.

Furthermore i linked my IBAction with the UIextfield that i would like to interact.
In fact i would like to add + or - or / or * to the number in the UITextFieldand do the math with an another and display
the result in the same UITextField.

Regards

http://i.stack.imgur.com/dIscv.png

Answer

First of all change your selector syntax like this.

UIBarButtonItem(title: "+", style: UIBarButtonItemStyle.done, target: self, action: #selector(self.sayHello(_:)))

Now in swift 3.0 you need to pass the name of first parameter, so change your sayHello action like this.

func sayHello(_ sender: UIBarButtonItem) {
     theTextField.text = "Hello!"
}

Note: The parameter type of method is either AnyObject or UIBarButtonItem, not the NSButton as on the above answer.