I have 3 textfields. I'm trying to make it have a Next button to go to from 1st to 2nd, and 2nd to 3rd, and a Done button once finished with the 3rd.
This is my code:
import Foundation
import UIKit
import Darwin
class View3on3 : UIViewController, UITextFieldDelegate {
#IBOutlet weak var APTeams: UITextField!
#IBOutlet weak var APRounds: UITextField!
#IBOutlet weak var APBreakers: UITextField!
#IBOutlet weak var ToAPBreak: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
APTeams.delegate = self
APRounds.delegate = self
APBreakers.delegate = self
ToAPBreak.backgroundColor = UIColor.clearColor()
ToAPBreak.layer.cornerRadius = 11
ToAPBreak.layer.borderWidth = 1
ToAPBreak.layer.borderColor = self.view.tintColor.CGColor
}
func initializeTextFields()
{
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (textField == APTeams){
APRounds.becomeFirstResponder()
} else if (textField == APRounds){
APBreakers.becomeFirstResponder()
} else if (textField == APBreakers){
APBreakers.resignFirstResponder()
} else {
//etc//
}
return true
}
This isn't working at all. What do I have to do?
For NumberPad type keyboard types iOS not able to display the return key.So you may try like this.
func initializeTextFields()
{
APTeams.keyboardType = UIKeyboardType.NumbersAndPunctuation
APRounds.keyboardType = UIKeyboardType.NumbersAndPunctuation
APBreakers.keyboardType = UIKeyboardType.NumbersAndPunctuation
APTeams.returnKeyType = UIReturnKeyType.Next
APRounds.returnKeyType = UIReturnKeyType.Next
APBreakers.returnKeyType = UIReturnKeyType.Done
}
Related
I've found a few threads here about this, and some videos online about it as well, but every solution seems to have problems reported by others. The simplest solution I've found is the one below.
import UIKit
class SignupController: UIViewController, UITextFieldDelegate {
// Outlets
#IBOutlet weak var logoImage: UIImageView!
#IBOutlet weak var nameTF: CustomTextField!
#IBOutlet weak var emailTF: CustomTextField!
#IBOutlet weak var passwordTF: CustomTextField!
#IBOutlet weak var confirmPassTF: CustomTextField!
// Actions
#IBAction func signupButton(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
logoImage.image = UIImage(named: "logo2")
nameTF.delegate = self
emailTF.delegate = self
passwordTF.delegate = self
confirmPassTF.delegate = self
}
// Moves to next text field each time return key is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTF {
textField.resignFirstResponder()
emailTF.becomeFirstResponder()
} else if textField == emailTF {
textField.resignFirstResponder()
passwordTF.becomeFirstResponder()
} else if textField == passwordTF {
textField.resignFirstResponder()
confirmPassTF.becomeFirstResponder()
}else if textField == confirmPassTF {
textField.resignFirstResponder()
}
return true
}
// Dismisses keyboard when tapped
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
It works, is very simple, but my project and coding experience are in their infancy, so I'm not sure if this is the best method simply because it's short, or if there's something I'm missing due to lack of experience/knowledge?
Anybody know of a better solution, or is this one just fine?
just do this:
class viewController: UIViewController, UITextFieldDelegate {
// Outlets
#IBOutlet weak var logoImage: UIImageView!
#IBOutlet weak var nameTF: CustomTextField!
#IBOutlet weak var emailTF: CustomTextField!
#IBOutlet weak var passwordTF: CustomTextField!
#IBOutlet weak var confirmPassTF: CustomTextField!
// Actions
#IBAction func signupButton(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
logoImage.image = UIImage(named: "logo2")
nameTF.delegate = self
emailTF.delegate = self
passwordTF.delegate = self
confirmPassTF.delegate = self
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dissMissKeyboard))
view.addGestureRecognizer(tap)
}
func dissMissKeyboard() {
view.endEditing(true)
}
I prefer to use UITextField delegate method:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
or setup inputAccessoryView which have 'done' or 'exit' button.
Then you need to implement the gesture recognition for this . Or you can do like this :
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dissMissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dissMissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
I am having some problems with function textFieldShouldReturn as far at i understand it should be called when enter are pressed on the keyboard but it does not. I have tried to search for solution on google and here but have not found a answer that solved the problem because most of the answers here on the webpage i have fund are a 3 years or older and the solutions from those did not help much.
I am using it in a UIView where the delegates for the textField is set in the function awakeFromNib() and i have tried some other delegate function textViewDidChangeSelection that does work so i am at a lost why it is not working.
Here is how the xib file looks
Here is the code that i am using as a popup:
import UIKit
class CuePointPopup: UIView,UITextFieldDelegate,UITextViewDelegate
{
#IBOutlet var labelCueNumberInImage: UILabel!
#IBOutlet var labelCueNumber: UILabel!
#IBOutlet var labelLayerName: UILabel!
#IBOutlet var labelPageNumber: UILabel!
#IBOutlet weak var view: UIImageView!
#IBOutlet var textFieldWhoText: UITextField!
#IBOutlet var textViewWhatText: UITextView!
#IBOutlet var textFieldWhereText: UITextField!
#IBOutlet var textFieldPageNumber: UITextField!
#IBOutlet var textFieldCueText: UITextField!
#IBOutlet var boxArrowLeft: UIImageView!
#IBOutlet var boxArrowRight: UIImageView!
#IBOutlet var boxArrowLeftTopConstraint: NSLayoutConstraint!
#IBOutlet var boxArrowRightTopConstraint: NSLayoutConstraint!
var cuePointObj:CuePoint!
var blockBtnClickedSave:((CuePoint) -> ())!
var blockBtnClickedCancel:((CuePoint) -> ())!
var blockBtnClickedDelete:((CuePoint) -> ())!
var blockTextChangedForPageNumber:((String, CuePoint) -> ())!
#IBOutlet var btnOutletVisibleOnPage: UIButton!
var isVisible = false
class func loadNib() -> CuePointPopup
{
return Bundle.main.loadNibNamed("CuePointPopup", owner: self,options: nil)!.last as! CuePointPopup
}
override func awakeFromNib() {
self.textFieldWhoText.delegate = self
self.textViewWhatText.delegate = self
self.textFieldWhereText.delegate = self
self.textFieldCueText.delegate = self
textViewWhatText.text = "Hello"
}
func setViewData(cueModel:CuePoint) {
self.cuePointObj = cueModel
labelCueNumberInImage.text = cueModel.cueNumber
labelCueNumber.text = "Cue #:" + cueModel.cueNumber
labelLayerName.text = "Layer #:" + cueModel.layerName
labelPageNumber.text = "Page #:" + cueModel.pageNumber
textFieldPageNumber.text = cueModel.pageNumber
textFieldWhoText.text = cueModel.whoString
textViewWhatText.text = cueModel.whatString
textFieldWhereText.text = cueModel.whereString
textFieldCueText.text = cueModel.cueTextString
if cueModel.isVisibleOnPage == true {
btnOutletVisibleOnPage.setImage(UIImage(named: "SelectedBox"), for: [])
btnOutletVisibleOnPage.tag = 1
}else{
btnOutletVisibleOnPage.setImage(UIImage(named: "UnselectedBox"), for: [])
btnOutletVisibleOnPage.tag = 0
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.text != "" {
if blockTextChangedForPageNumber != nil {
self.blockTextChangedForPageNumber(textField.text!, self.cuePointObj)
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//self.view.endEditing(true)
if self.textFieldWhoText.isEditing {
self.textFieldWhoText.endEditing(true)
} else if self.textFieldCueText.isEditing{
self.textFieldCueText.endEditing(true)
} else if self.textFieldWhereText.isEditing {
self.textFieldWhereText.endEditing(true)
} else {
self.textViewWhatText.endEditing(true)
}
//self.view.endEditing(true)
return false
}
}
Here is how i load the XIB
#IBOutlet weak var bookView: UIView!
var objCuePopup:CuePointPopup!
if objCuePopup != nil {
objCuePopup.removeFromSuperview()
}
objCuePopup = CuePointPopup.loadNib()
objCuePopup = CuePointPopup.loadNib()
objCuePopup.frame = CGRect(x:cuePointModal.cueX, y:0, width:465, height:410)
objCuePopup.center = CGPoint(x:objCuePopup.center.x, y:cuePointModal.cueY + 5)
//Set Y value for Popup View
if objCuePopup.frame.origin.y < bookView.frame.origin.y {
objCuePopup.frame.origin.y = bookView.frame.origin.y
}
let popupMaxY = objCuePopup.frame.maxY
let bookViewMaxY = bookView.frame.maxY
if popupMaxY > bookViewMaxY {
objCuePopup.frame.origin.y = bookViewMaxY - objCuePopup.frame.size.height
}
//Set X value for Popup View
if cuePointModal.cueX > 455 {
objCuePopup.frame.origin.x = cuePointModal.cueX - 455
objCuePopup.boxArrowLeft.isHidden = true
objCuePopup.boxArrowRight.isHidden = false
let rightY = cuePointModal.cueY - objCuePopup.frame.origin.y
objCuePopup.boxArrowRightTopConstraint.constant = rightY + 3
}else{
objCuePopup.frame.origin.x = cuePointModal.cueX + 40
objCuePopup.boxArrowLeft.isHidden = false
objCuePopup.boxArrowRight.isHidden = true
let leftY = cuePointModal.cueY - objCuePopup.frame.origin.y
objCuePopup.boxArrowLeftTopConstraint.constant = leftY + 3
}
objCuePopup.setViewData(cueModel: cuePointModal)
objCuePopup.textFieldWhoText.delegate = self
objCuePopup.textFieldWhereText.delegate = self
objCuePopup.textViewWhatText.delegate = self
objCuePopup.textFieldCueText.delegate = self
bookView.addSubview(objCuePopup)
I hope that someone here can help me with this problem.
I took text field outlet collection and bind six text field over there.
I want to becomeFirstResponder of next text field which is in text field outlet collection.
I gave textfields tag 0 to 5 from storyboard.
see,
Main ViewController:
class ViewController: UIViewController {
#IBOutlet var txtSignUp: [UITextField]!
var arrayPlaceHolder:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
arrayPlaceHolder = NSArray(array: ["1","2","3","4","5","6"])
self.setTextFieldValue()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setTextFieldValue(){
for txtField in txtSignUp{
let tagTxt = txtField.tag
txtField.attributedPlaceholder = NSAttributedString(string:arrayPlaceHolder[tagTxt] as! String, attributes:[NSForegroundColorAttributeName:UIColor.black])
if(tagTxt != ((arrayPlaceHolder.count) - 1)){
txtField.returnKeyType = .next
}
txtField.delegate = self
}
}
}
extension ViewController:UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
for txt in txtSignUp{
let nextTxt = (textField.tag + 1)
if txt.tag == nextTxt {
txt.becomeFirstResponder()
break
}
}
return true
}
}
Error:
whose view is not in the window hierarchy!
Explanation:
In this code, I am not able to become next text field as becomeFirstResponder.
Can anyone help me to resolve this issue.
On TVos you have to use the textFieldDidEndEditing function because textFieldShouldReturn won't work to set the next responder:
class MyViewController: UIViewController{
#IBOutlet weak var firstTextField: UITextField!
#IBOutlet weak var secondTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
firstTextField.delegate = self
secondTextField.delegate = self
firstTextField.tag = 0
secondTextField.tag = 1
}
}
extension MyViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if (textField.tag == 0){
secondTextField.becomeFirstResponder()
}
}
}
I am new to Swift language. I'm trying to use SwiftValidator library from #jpotts18. I got to use rules and validate UITextFields but I can't get them to normal state if they're correct.
This is my view controller
class SignUpViewController: UIViewController, ValidationDelegate {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var rePasswordTextField: UITextField!
let validator = Validator()
override func viewDidLoad() {
super.viewDidLoad()
validator.registerField(nameTextField, rules: [RequiredRule(), FullNameRule()])
}
func validationSuccessful() {
print("success")
}
func validationFailed(errors: [(Validatable, ValidationError)]) {
for (field, _) in errors {
if let field = field as? UITextField {
field.layer.borderColor = UIColor.redColor().CGColor
field.layer.borderWidth = 1.0
}
}
}
#IBAction func onRegisterClick(sender: UIButton) {
validator.validate(self)
}
}
My view turns red if validation fails but if it doesn't I don't know what code should I use to return that specific UITextField to normal state.
Any suggestions?
Thanks.
After some trial and error I managed to do what I want with this code.
validator.styleTransformers(success: {
(validationRule) -> Void in
print("Field Validated")
if let textField = validationRule.field as? UITextField {
textField.textColor = UIColor.blackColor()
}
}, error: {
(validationError) -> Void in
print("Field Incorrect")
if let textField = validationError.field as? UITextField {
textField.textColor = UIColor.redColor()
}
})
I've done plenty of searching but am not finding the answer to my question.
My two UITextFields fields are resetting using the clear function. The UILabel retains the original value from the printWatts function, doesn't clear. Would appreciate any advice to resolve this small issue as I learn Swift. Thanks!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var inputFeet: UITextField!
#IBOutlet weak var inputWatts: UITextField!
#IBOutlet weak var resultsLabel: UILabel!
var stripFeet = ""
var wattValue = ""
var totalWatts : Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func submitButton(sender: AnyObject) {
calculateWatts()
}
#IBAction func clearButton(sender: AnyObject) {
clear()
}
func calculateWatts() {
if let stripFeet = inputFeet.text,
wattValue = inputWatts.text,
fstripFeet = Float(stripFeet),
fwattValue = Float(wattValue){
totalWatts = fstripFeet * fwattValue
}
printWatts()
}
func printWatts() {
let formatWatts = String(format: "%0.2f", totalWatts)
resultsLabel.text = "Total watts: \(formatWatts)"
}
func clear(){
inputFeet.text = ""
inputWatts.text = ""
self.resultsLabel.text = ""
}
}
Thanks to #Eendje for suggesting that I check my connections. I had the submit and clear actions both connected to my submit button. Option drag is too convenient. All good now.