I have three UITextfields (customerRequestTextField , fundsAvailableTextField and amountOwedMarketTextField) on the same ViewController.
I would like to set up the amountOwedTextField so that it automatically updates its field by subtracting the data entered into the other two textfields (customerRequestTextField - fundsAvailableTextField).
Should I use NSNotifications? Or a selector? Or something else?
I have tried setting up a selector, but my version does not work.
This is declared globally.
var amountOwedToMarket
This code is located in the viewDidLoad().
amountOwedMarketTextField.text = String(amountOwedToMarket)
amountOwedMarketTextField.addTarget(self, action: #selector(self.textFieldDidChange(sender:)), for: .editingChanged)
}
This is declared outside of the viewDidLoad()
#objc func textFieldDidChange(sender: UITextField) -> Int {
return Int(amountCustomerRequestTextField.text!) ?? 21
}
You need to add the target to textfields that you want to listen to their changes
// in viewDidLoad
amountCustomerRequestTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
fundsAvailableTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
#objc func textFieldDidChange(_ sender: UITextField) {
if let first = Int(amountCustomerRequestTextField.text!) , let second = Int(fundsAvailableTextField.text!) {
amountOwedMarketTextField.text = "\(first - second)"
}
}
Related
Is there any way in which I can send information from a textfield to a label automatically while writing for example if I have 2 texfield and 1 label
one by name and the other by last name
that when writing a single letter or a name this automatically appears in the label
some way to do this with de button
-> #IBAction func bt(_ sender: Any) { text =texfield!.text text = txfield!.text text.text = "\(textt!) \(texxt!)"
You can add this text change listener in your viewDidLoad method of View Controller.
yourTextField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
And add this function to your View Controller
#objc func textFieldDidChange(_ textField: UITextField) {
yourLabel.text = textField.text
}
I have an addTarget set up on UITextField that clears the placeholder text when editingDidBegin. But I don't know how to restore the placeholder text if the user clicks on another UITextField, or the field is left empty.
This is located in viewDidLoad()
firstInitialTextField.addTarget(self, action: #selector(clearPlaceholderInTextField), for: UIControl.Event.editingDidBegin)
This function is located in the main body of the program.
#objc func clearPlaceholderInTextField() {
firstInitialTextField.placeholder = ""
}
I have several fields I would like to apply this same functionality to.
Create outlet collection for all the textfields like
#IBOutlet var textFs:[UITextField]!
with different tag for each , And array of placeHolders that you set in viewDidLoad
var placeholders = [String]()
Then set the vc as the delegate for all of them in viewDidLoad
textFs.forEach { $0.delegate = self }
Implement
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.placeholder = ""
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.placeholder = placeholders[textField.tag]
}
I am new in swift. On executing this app login screen goes to sign in.On selecting "Already have account sign up".You get to sign up view. In the sign up trying to develop the picker view.These are two issues arise while developing picker view
1) picker view should be hidden on loading view controller .but picker view is visible as view controller appear?
2) In date of birth pickview when a done button on date picker view is selected the app crash .but it should display the corresponding date in a text field?
func showDatePicker(){
//Formate Date
datePicker.datePickerMode = .date
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action: "cancelDatePicker")
toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
dateTextField.inputAccessoryView = toolbar
dateTextField.inputView = datePicker
}
func donedatePicker(){
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
dateTextField.text = formatter.string(from: datePicker.date)
self.view.endEditing(true)
}
func cancelDatePicker(){
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pickerView.delegate=self
pickerView.dataSource=self
genderTextField.inputView=pickerView
showDatePicker()
}
How to avoid this crash. You can download the project from this link https://drive.google.com/file/d/1a6Pmw2gVDwLP9grL8tG72NBx-tKwZozI/view?usp=sharing
you miss few things in view did load I had updated the code
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate=self
pickerView.dataSource=self
genderTextField.inputView = pickerView
genderTextField.delegate = self
dateTextField.delegate = self
}
Assign the text field delegate and implement the function textFieldShouldBeginEditing function for showing the Date Picker
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField.tag == 1 { //Date Text Field
showDatePicker()
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
I had assigned the tag value of Date Text Field from the storyboard and hide the picker view from the storyboard. It will solve your both points
First you need to give delegate to UITextField i.e
dateTextField.delegate = self
and then you need to confirm with UITextFieldDelegate method with sign up class i.e
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == dateTextField {
self.showDatePicker()
}
}
Use this above code may it helps you.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pickerView.delegate=self
pickerView.dataSource=self
genderTextField.inputView=pickerView
showDatePicker()
}
The mistake is here. When the view is load in viewDidLoad, date picker is show itself. So you must add a action for click to show you picker view and call it in there.
For example
#objc fileprivate func showIt(_ sender:UIButton){
showDatePicker()
}
Also your action must be set wit #selector
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
changed to
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: #selector(donedatePicker))
And for error #1 you must be make firstResponder UITextField somehow, you must resign it.
Can you add this function for textFieldDelegate.
extension YourViewController: UITextFieldDelegate{
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.isFirstResponder{
showDatePicker()
}
}
}
you should b calling this showDatePicker() on a tap at date textfield.
func textFieldDidBeginEditing(_ textField: UITextField) {
let datePicker = UIDatePicker()
if startDateTxt == textField{
textField.inputView = datePicker
datePicker.addTarget(self, action: #selector(showDatePicker()), for: .valueChanged)
}
}
and for 2nd error:
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: #selector(donedatePicker))
I have a date picker I am using to set the value of a text field. It works great except that it only works the 2nd time that I tap into the text field, that is, the first time I tap the text field it shows me the standard keyboard. Then if I tap out of the textfield and back into it, it shows the datepicker. I've tried different variations of it, but it either doesn't work at all, or I get the same problem. This is how I set it up:
class ExpDateTableViewCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
#IBAction func textFieldEditing(sender: UITextField) {
let datePickerView:UIDatePicker! = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(ExpDateTableViewCell.datePickerValueChanged), for: UIControlEvents.valueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.none
textField.text = dateFormatter.string(from: sender.date)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The problem is this code:
#IBAction func textFieldEditing(sender: UITextField) {
// ...
sender.inputView = datePickerView
}
You are not setting the text field's inputView to the picker view until after the first time we have started editing. Thus we get the effect you correctly described: the second time we edit, the picker view is present.
You need to set the text field's inputView much earlier, such as in awakeFromNib, before the user has a chance to edit the text field for the first time.
First make UIDatepickerview as a inputview for textfield
Add this code inside the textfield action
#IBAction func textFieldEditing(sender: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), forControlEvents: UIControlEvents.ValueChanged)
}
I am trying to create 4 UIButtons that highlight and stay highlighted when they are clicked. The only problem is I need only one UIButton to be Highlighted at a time. So, if there is a UIButton highlighted already, I need it to be "unhighlighted" and highlight the UIButton I clicked. I have tried to do this before and failed. Please help me with this problem.
I am using the Swift coding language to do this.
Any input or suggestions would be greatly appreciated.
If you give this answer an upvote, remember to upvote dasblikenlight's answer as well.
class ViewController: UIViewController {
// Connect all 4 buttons to this outlet
#IBOutlet var radioGroup: [UIButton]!
// Connect this action to all 4 buttons
#IBAction func radioGroupClicked(sender: AnyObject) {
// Unhighlight all buttons
unhighlightRadioGroup()
// Highlight the one being clicked on
highlightRadioGroup(sender as! UIButton)
}
// Set all 4 buttons in unselected state
func unhighlightRadioGroup() {
for button in radioGroup {
button.selected = false
}
}
// Set one button in the selected state
func highlightRadioGroup(button : UIButton) {
button.selected = true
}
}
You can do it with an IBOutletCollection. Command-drag one of the buttons into the view controller code, and choose creating of an IBOutletCollection on drop, and name your collection something - say, radioGroup. Then control-drag the remaining three buttons into the same IBOutletCollection.
Next thing is to add a method to un-highlight all buttons in your radioGroup. This can be done with a simple loop.
Finally, add calls to unhighlightRadioGroup from the event handler of your buttons. Event handler should first call your unhighlightRadioGroup method, and then highlight the sender received in the event handler.
lazy var buttonsArray: [UIButton] = {
var buttons = [UIButton]()
let firstButton = UIButton()
let secondButton = UIButton()
let thirdButton = UIButton()
let fourthButton = UIButton()
buttons = [firstButton, secondButton, thirdButton, fourthButton]
return buttons
}()
private func setupButtonMethods() {
filteredButtons[0].addTarget(self, action: #selector(firstButtonPressed(sender:)), for: .touchUpInside)
filteredButtons[1].addTarget(self, action: #selector(secondButtonPressed(sender:)), for: .touchUpInside)
filteredButtons[2].addTarget(self, action: #selector(thirdButtonPressed(sender:)), for: .touchUpInside)
filteredButtons[3].addTarget(self, action: #selector(fourthButtonPressed(sender:)), for: .touchUpInside)
}
private func setupHiglightedStateOnButton(button: UIButton) {
for btn in buttonsArray {
btn.isSelected = false
btn.backgroundColor = .gray
btn.setTitleColor(.white, for: .normal)
btn.isUserInteractionEnabled = true
}
button.isSelected = true
button.backgroundColor = .yellow
button.setTitleColor(.black, for: .normal)
button.isUserInteractionEnabled = false
}
#objc func firstButtonPressed(sender: UIButton) {
setupHiglightedStateOnButton(button: sender)
}
#objc func secondButtonPressed(sender: UIButton) {
setupHiglightedStateOnButton(button: sender)
}
#objc func thirdButtonPressed(sender: UIButton) {
setupHiglightedStateOnButton(button: sender)
}
#objc func fourthButtonPressed(sender: UIButton) {
setupHiglightedStateOnButton(button: sender)
}
remember to call setupButtonMethods() inside viewDidLoad()