How to create a custom UITextField prepackaged with its own formatting behavior? - swift

I am trying to make a reusable textfield that will format its contents to be in a currency format without relying on a containing viewcontroller to implement this behavior for it.
Right now the viewcontroller that the textfield is in is implementing the desired behavior in a TextFieldChange action and it works fine:
class MyViewController: UIViewController {
#IBOutlet weak var TextField: UITextField!
...
...
#IBAction func TextFieldChanged(_ sender: Any) {
// Format text in text field
}
}
This works, but that means I'll have to copy and paste this code into every viewcontroller that I want to have this functionality. I would like it so I could just assign the textfield its own class in the inspector so that this behavior will be a part of every textfield I make using this class. How do I do this?

Related

Open keyboard without clicking on TextField on tvOS - Swift

I'm creating an app and I need to login to it and I don't want to use 2 Text Field for insert Email and Password. What I would wish to achieve is: click on the button "Log in", then it will open the classic full screen keyboard that is usually appearing when you are doing click on UITextField in tvOS.
Can someone please write an example of code on how to invoke the keyboard clicking on a UIButton instead of UITextField? Thanks a lot!
While your UI is questionable, once your first text field finishes editing, you could start the other one.
Set the first text field UITextFieldDelegate to the view controller, and then:
class ViewController: UIViewController , UITextFieldDelegate{
#IBOutlet weak var tf2: UITextField!
#IBOutlet weak var tf1: UITextField!
#IBAction func click() {
tf1.becomeFirstResponder()
}
func textFieldDidEndEditing(_ textField: UITextField) {
if (textField == tf1){
tf2.becomeFirstResponder()
}
}
}
If you want a UITextField to open up the keyboard without the user having to tap on it, you can use yourTextField.becomeFirstResponder().
I don't think you can present the keyboard without any associated input view

How do you get a text field input in you view controller code?

I’m trying to make Xcode print "Nice!" when you type in "Hi". I've used a IBOutlet, but I don’t know how to use the user input in my code. Also BTW I'm using Storyboard and not SwiftUI. It also gives me an error when I try to compare the datatype UIViewController and a String. Here is my view controller code(with the default App Delegate and Scene Delegate code):
import UIKit
class ViewController: UIViewController {
#IBOutlet var yeet: [UITextField]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func fuel(_ yeet:UIViewController) -> Int {
if yeet == ("hi") {
print("Nice!")
}
}
}
your textfield show be setup as
#IBOutlet weak var textFeildName: UITextField!
you will need to change a couple things inside of your file to prevent a crash. I'd delete the textfield and drag it into the assistant view and give it a new name.
but before you press "connect" press the "outlet" tab and change it to "Action" and then a new selector should come up select "Editing Did End" and go to the top and press "Did End On Exit"
after that is done would want to reference the variable of the text field:
example:
#IBAction func TextFieldName(_ sender: Any) {
if(self.TextFeildName.text!.contains("hi")){
print("Nice!")
}
}
On top of all this, you do not compare strings with == that's only if you compare 2 separate strings for example stringOne == stringTwo if you are comparing or asking if a string contains anything you'd want to use the developing language specific string container IE: .contains
Also, please do not include "Xcode" as a tag with your question, as that should be reserved for Xcode related problems. not Swift or objective-c coding issues.

Detect backspace in empty UITextField Swift Working Sample

I know that this question may sounds duplicate, but looking at the several answer, nothing is working for me yet.
Basically I have a Quizz App, a question is shown and the user needs to fill several UITextFields to answer the question (i.e. if the answer is VENICE, 6 UITextFields will be shown, 1 per letter).
It was able to detect one character in the UITextFields and once the user hits a key it will jump to the following UITextField. I use the tag of the UITextField and the method becomeFirstResponder.
The problem is that I will like to detect the backspace when a UITextField is empty so I will jump to the previous UITextField.
I have tried this solution from Jacob Caraballo (Detect backspace in empty UITextField) but I am not sure, how to use it with my existing UITextField.
For example, I have tried:
// #IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField1:MyTextField!
But calling the delegate
textField1.myDelegate = self
It crashes
I also notice, that using the Jacob's solution I won't be able to check which UITextField was used as the func textFieldDidDelete() doesn't not have an UITextField as parameter and I will need to check its tag i.e.
If textField.tag == 5 {
textField4.becomeFirstResponder()
}
Any help on this please?
If you use Jacob's solution, the deleteBackward method will be called with the current UITextField instance. So you can add a protocol to that UITextField class and pass it back to your view.
Something like this:
protocol MyTextFieldDelegate: class {
func backwardDetected(textField: MyTextField)
}
class MyTextField: UITextField {
weak var myTextFieldDelegate: MyTextFieldDelegate?
override func deleteBackward() {
super.deleteBackward()
self.myTextFieldDelegate?.backwardDetected(textField: self)
}
}

Swift: How to link Touch Bar controls to main window controls

I'm new to Swift/macOS dev, plenty of dev experience otherwise though. Just trying to make something rudimentary.
Here's my app storyboard:
I'm trying to get:
the Touch Bar slider to change when the slider on the main window changes
vice versa
update the Touch Bar Label button with the Int value of the slider.
Q) How do I achieve this?
Note: The main window slider control is wired up and working when I manipulate it e.g.
#IBOutlet weak var mySlider: NSSlider!
#IBAction func mySlider_Changed(_ sender: NSSlider) {
//... stuff happens here.
}
You'll want your view controller to have some explicit model/state of what the value of these sliders have. e.g.
class ViewController : NSViewController {
var value: Double
}
Then you can connect the sliders and textfield to update or display this value.
Approach 1: Target/Action/SetValue
This follows the use of explicit IBActions that you had started. In response to that action, we'll pull the doubleValue from the slider and update the ViewController's model from that:
#IBAction func sliderValueChanged(_ sender: NSSlider) {
value = sender.doubleValue
}
The second piece is updating everything to reflect that new value. With Swift, we can just use the didSet observer on the ViewController's value property to know when it changes and update all of the controls, e.g:
#IBOutlet weak var touchBarSlider: NSSlider!
#IBOutlet weak var windowSlider: NSSlider!
#IBOutlet weak var windowTextField: NSTextField!
var value: Double {
didSet {
touchBarSlider.doubleValue = value
windowSlider.doubleValue = value
windowTextField.doubleValue = value
}
}
And that's it. You can add a number formatter to the textfield so it nicely displays the value, which you can do in Interface Builder or programmatically. And any other time you change the value, all of the controls will still get updated since they are updated in the didSet observer instead of just the slider action methods.
Approach 2: Bindings
Bindings can eliminate a lot of this boiler plate code when it comes to connecting model data to your views.
With bindings you can get rid of the outlets and the action methods, and have the only thing left in the view controller be:
class ViewController: NSViewController {
#objc dynamic var value: Double
}
The #objc dynamic makes the property be KVO compliant, which is required when using bindings.
The other piece is establishing bindings from the controls to our ViewController's value property. For all of the controls this is done by through the bindings inspector pane, binding the 'Value' of the control to the View Controller's value key path:
And that's it. Again, you could add a number formatter to the textfield, and any other changes to the value property will still update your controls since it will trigger the bindings to it. (you can also still use the didSet observer for value to make other changes that you can't do with bindings)

IBOutlet and IBAction in Swift

I connected a IBOutlet and IBAction to my button variable from Interface Builder to my View Controller. How do I add an action method to the button in Swift?
This code doesn't seem to work.
#IBOutlet var OK: UIButton!
#IBAction func OK(sender: UIButton){}
The Objective-C equivalent I found is:
#interface Controller
{
IBOutlet id textField; // links to TextField UI object
}
- (IBAction)doAction:(id)sender; // e.g. called when button pushed
When you attach a button to the viewController and create an action (IBAction) using ctrl-drag, you create a method that looks likes this in Swift (if it doesn't have arguments):
#IBAction func buttonAction() {}
In Objective-C the same thing will look like this:
- (IBAction)buttonAction {}
So that means that #IBAction func OK(sender: UIButton){} is an action method.
If you want to know about the sender argument, I would recommend this SO post.
Edit:
For what you want to do, I create an IBOutlet and an IBAction, that way I can change its attributes with the outlet variable, and have the action side of things with the IBAction, like what you show above:
#IBOutlet var OK: UIButton!
#IBAction func OK(sender: UIButton){}
For example, if I want to hide the button, I would put this code in the viewDidLoad
OK.hidden = true
The OK in that code is for the outlet variable, if I wanted to print "You pressed me" to the console when the button is pressed, I would use this code:
#IBAction func OK(sender: UIButton){
println("You pressed me")
}
Above I am using the action to print "You pressed me" to the console.
A few things to note:
When Swift 2.0 gets released println will get changed to print. Also with you action and outlet, I would suggest giving them differing names, to make it easier to differentiate the two, something like this:
#IBOutlet var okOutlet: UIButton!
#IBAction func okAction(sender: UIButton){}
Along with that, you should use camel case when naming variables, constants, functions, etc.
One way to do it, is control-drag from your button to your viewcontroller and choose action:
If you have connected your button's action, your code should work just fine.
Here are the steps you can follow-
For #IBOutlet
1.Declare Your Interface builder Element property right after class name
class SomeViewController: UIViewController{
#IBOutlet weak var aTextField : UITextField! ////Your Interface builder Element
2.Hook the IB Element From Storyboard.
For #IBAction
1.Write A method inside your class(say SomeViewController)
#IBAction func anAction(_sender : AnyObject){
}
2.Hook the method from Storyboard.
Hope it might helps.
You can simply add action from your storyboard. See the image.