SCLAlertView - Focus on textfield - swift

I have a SCLAlertView with a textfield inside it. How can I make that textfield become first responder so that when the alert view is shown, i can automatically start writing instead of clicking on the textfield first?

After showing alert you can put this code at the end of function.
#IBAction func showEdit(_ sender: AnyObject) {
let appearance = SCLAlertView.SCLAppearance(showCloseButton: true)
let alert = SCLAlertView(appearance: appearance)
let txt = alert.addTextField("Enter your name")
_ = alert.addButton("Show Name") {
print("Text value: \(txt.text ?? "NA")")
}
_ = alert.showEdit(kInfoTitle, subTitle:kSubtitle)
//Add this code in show function to set textfield as first responder
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
txt.becomeFirstResponder()
}
}
If you have more than one textfield than you have to set first textfield as first responder.

Related

SwiftUI - how can I have a long press gesture trigger an alert with text view and then drop an mkannotationpin with the text as it’s title?

very new to swiftUI but I couldn't find this answer anywhere. Thanks in advance.
At the end of a LongPressGesture, I have this gesture recogniser method called, which executes fine. The only problem is I want to call showAlert() and wait for the text entry which updates the annotationName variable. This is meant to be the title of my annotation pin.
The problem is the showAlert function and TextField only shows up when the handlePress function has completed. I have checked it in debugger. So the functionality of this code is such that parent.locationName is always the previous TextField entry.
I've looked into async functions but I'm not sure if that can be implemented with the gesture recogniser.
Essentially what I am intending is:
handlePress() calls showAlert() which executes before returning to the rest of handlePress()
At the moment it is:
handlePress() calls showAlert() however showAlert() executes at the end of handlePress (eg. the displaying of textEntry field appears after the annotation has been added)
#objc func handlePress(gesture: UIGestureRecognizer) {
// want this to run and show alert, which is a text entry and updates
// parent.locationName
showAlert(alert: alert())
var annotationName = parent.locationName
if gesture.state == .ended {
if let mapView = gesture.view as? MKMapView {
let point = gesture.location(in: mapView)
let coordinate = mapView.convert(point, toCoordinateFrom: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = annotationName
mapView.addAnnotation(annotation)
}
}
}
Maybe you could use alert action callback
struct ContentView: View {
#State var showingAlert: Bool = false
func actionAfterAlert() {
print("Action after press Ok")
}
var body: some View {
VStack {
Text("Hello, world!")
.padding()
.onLongPressGesture {
showingAlert = true
}
}
.alert(isPresented: $showingAlert) { () -> Alert in
Alert(title: Text("iOS Alert"), message: Text("Alert"), primaryButton: .default(Text("Ok"), action: {
actionAfterAlert()
}), secondaryButton: .default(Text("Dismiss")))
}
}
}

Resigning textfield by clicking on other textfield in swift

i have three text fields. one is for showing date picker, second is to showing options for gender and another one is for showing country code. let say gender dropdown box is showing now, if i will click on dateofbirth or contrycode textfield, then gender will be hidden. like that if date of birth is showing and i will click gender or country code textfield , then date of birth textfield will be hidden. same will work for countrycode.
code for showing gender textfield:-
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
if textField == gender_TextField{
tableViewOne.snp.updateConstraints { (make) in
make.top.equalTo(textField.frame.maxY)
make.left.equalTo(textField.frame.origin.x)
make.right.equalTo(0-(self.containerView.frame.maxX-textField.frame.maxX))
make.height.equalTo(0)
}
self.containerView.layoutIfNeeded()
UIView .animate(withDuration: 0.4, animations: {
self.tableViewOne.snp.updateConstraints({ (make) -> Void in
make.height.equalTo(130)
})
self.containerView.layoutIfNeeded()
}, completion: nil)
if(textField == gender_TextField){
self.selectedTextfeild = 1
self.selectedTextFieldType = DROPDOWN_TEXTFIELD.gender
}
tableViewOne.tableFooterView = UIView()
tableViewOne.reloadData()
tableViewOne.isHidden = !isTableViewHiden
isTableViewHiden = !isTableViewHiden
return false
}
return true
}
code for showing date picker
datePickerView.addTarget(self, action: #selector(dateChanged(datePicker:)), for: .valueChanged)
datePickerView.datePickerMode = .date
dob_TextField.inputView = datePickerView
datePickerView.maximumDate = Date()
code for showing countrycode
countryPickerView.delegate = self
if countryPickerView.selectedCountry.phoneCode != "+93"{
countryCode_Lable.text = countryPickerView.selectedCountry.phoneCode
}
else{
countryCode_Lable.text = "+1"
}
You can hide the other two views and can resign the other two textFields when one is active.

How to determine the last activ UITextField in Xcode

I am new to swift and i am playing around with a little converter app. I Have two TextFields and one "convert" button.
I want to overwrite the non acticv Textfield with the converted value from the last activ TextField.
I know it would be easier with more Textfields and more buttons but i would like to solve it this way.
Can anybody give me an advise?
var NumberC = Int(InputCelcius.text!)!
var NumberF = Int(InputFahrenheit.text!)!
if InputCelcius.isFirstResponder {
if (InputCelcius.text?.isEmpty)! {
NumberC=0
print("NumberC is empty")
}
NumberC = NumberC * 9/5 + 32
InputFahrenheit.text = " \(NumberC)"
}
else if InputFahrenheit.isFirstResponder {
if (InputFahrenheit.text?.isEmpty)! {
NumberF=0
print("NumberF is empty")
}
NumberF = (NumberF - 32) * 5/9
InputCelcius.text = " \(NumberF)"
}
I’d suggest using the UITextFieldDelegate function textFieldDidEndEditing. Make sure you subclass your viewController as a UITextFieldDelegate.
class ViewController: UIViewController, UITextFieldDelegate {
Set each textField's delegate to self in viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
InputFahrenheit.delegate = self
InputCelsius.delegate = self
}
With this method you wouldn't even need a UIButton, but you could use the button to force the textField to end editing like this.
#objc func buttonAction (sender: UIButton) {
self.view.endEditing(true)
}
Which will call this delegate method if the user was editing a textField.
func textFieldDidEndEditing (textField: UITextField) {
if textField.isEmpty {return} //this prevents nil errors and user would have to type in "0" if wishing to convert zero.
if textField == InputCelsius {
let conversion = Float(textField.text!) * 9/5 + 32
InputFahrenheit.text = String(format: “%.f”, conversion) //“%.1f” will show one decimal place and so forth
} else if textField == InputFahrenheit {
let conversion = ( Float(textField.text!) - 32 ) * 5/9
InputCelsius.text = String(format: “%.f”, conversion)
}
}
I‘m not quite sure about that but I think if you press the button, the button itself will become first responder, so your code won‘t work.
The proper way to do that, would be to set IBAction functions that get called when you finish editing one of your textfields. Just connect the Textfields inside your storyboard to the code like you did it with your button.
Then you can set up two functions, one for each of the textfields, so you don‘t have to worry about firstresponder.

How to make a number pad appear without a text box

Hello I am trying to have a number pad appear after a timer is up. Then have my user type numbers on the pad and their input be saved to a variable in my code not a text box. I can't seem to find anything on popping up a number pad without using a text box. Any help is appreciated.
Ok I'm going to give you some code that will greatly help you. You need some sort of UITextView or UITextField to get the system keyboard. So essentially what we will do is have a textField without showing it, and then grab the info off it and store it into the variable.
//Dummy textField instance as a VC property.
let textField = UITextField()
//Add some setup to viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self //Don't forget to make vc conform to UITextFieldDelegateProtocol
textField.keyboardType = .phonePad
//http://stackoverflow.com/a/40640855/5153744 for setting up toolbar
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
//You can't get the textField to become the first responder without adding it as a subview
//But don't worry because its frame is 0 so it won't show.
self.view.addSubview(textField)
}
//When done button is pressed this will get called and initate `textFieldDidEndEditing:`
func dismissKeyboard() {
view.endEditing(true)
}
//This is the whatever function you call when your timer is fired. Important thing is just line of code inside that our dummy code becomes first responder
func timerUp() {
textField.becomeFirstResponder()
}
//This is called when done is pressed and now you can grab value out of the textField and store it in any variable you want.
func textFieldDidEndEditing(_ textField: UITextField) {
textField.resignFirstResponder()
let intValue = Int(textField.text ?? "0") ?? 0
print(intValue)
}
I am using storyboard and this is what I did:
drag-drop a text field
On the storyboard, in the attributes inspector (having selected the text field), under "Drawing", select hidden
make an outlet for the text field in your view controller
make sure your view controller extends the UITextViewDelegate
make your current view controller the delegate
in the required location simply call <textfieldOutlet>.becomeFirstResponder()
Now that this is simply a textfield's data, u can always store the value and use it else where.

Text reappearing in TextField after creating a new user

// Alright I need to clear the text field as soon as the logout button is pressed. "inputToolbar" is the variable I am using in the MessagesViewController, but the logout button is on another screen.
#IBAction func logoutUser(sender: AnyObject) {
let installation = PFInstallation.currentInstallation()
installation.setObject("", forKey: "user")
installation.saveInBackground()
PFUser.logOut()
MessagesViewController.inputToolbar.contentView.textView.resignFirstResponder()
//Segue to Splash Screen
self.navigationController?.popToRootViewControllerAnimated(true)
}
With:
MessagesViewController.inputToolbar.contentView.textView.resignFirstResponder()
You're dismissing the keyboard, which would not be in view at this point.
To clear the text view, you will need reset its text property with:
MessagesViewController.inputToolbar.contentView.textView.text = ""