简体   繁体   中英

Make TextField Active on Button Press

Alright so I have a toolbar that I'm using as an accessory so it only appears when the keyboard appears. I have that bit working by doing this;

@IBOutlet var toolBar: UIToolbar!
@IBOutlet weak var playerInput: UITextField!

override func viewDidLoad() {
  super.viewDidLoad()

  playerInput.delegate = self
  playerInput.inputAccessoryView = toolBar
}

To test its working, I just make a temporary textField in the view somewhere, and connected it as playerInput . But that's not what my design calls for in the end. I need the textField to be ON the toolbar being used as the accessory and have a button on my navigation bar that selects the textField like the user touched it so it brings up the keyboard, toolbar, and has focus.

Is it possible to have my button function @IBAction func addButton(){} act like the user touched the textField, so it brings up the keyboard and shows the toolbar?

EDIT: When I add playerInput.becomeFirstResponder() to my button @IBAction function, nothing happens. Running this on my iPhone 6s or the iPhone Simulator, pressing the button does nothing. Adding a console print to make sure the button is working, works just fine so I know the button is working.

EDIT 2: Ok, so I have a very terrible workaround to get something to happen. I added a 2nd textField to the main view and made it hidden. Then set my toolbar accessory view to the new hidden textField. So when the button is pressed, it calls the hidden textField as first responder, which attaches the toolbar that has the real textField on it. Then the user can selected the real textField and save their entry properly. That's all working for now. The only problem is if the user dismisses the keyboard by swiping down, the beyboard will reappear once, forcing them to swipe it closed again.

是的,您可以使用playerInput.becomeFirstResponder()实现此playerInput.becomeFirstResponder()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM