IBOutlet and IBAction in Swift - 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.

Related

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.

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

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?

Following Apple 'Food Tracker' tutorial for Xcode - can't get button to change label text

I'm following official iOS Apps tutorial to make a basic Single View Application in Xcode.
Literally all we have done so far is:
Added a label to the UI and set initial text to 'Meal name:'
Added a textbox to the UI
Added a button to the UI
Then we've added some very simple code to the View Controller declaring the label as an outlet and a button action which, when invoked, should change the label's text to Default Text.
My ViewController code is now identical to the tutorial code namely:
class ViewController: UIViewController {
//MARK: Properties
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var mealNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Actions
#IBAction func setDefaultLabelText(_ sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
The problem is that when I press the button in simulator, I get an error message saying an implicitly unwrapped optional value is nil. (app launches fine, it's just when pressing the button)
As I understand it this means something is blank that can't be, but the only optionals I have are:
The textbox, which isn't blank because before I press the button I write 'biscuits' or something in it
The label text, which isn't blank because it's set to 'Meal name:' by default
I really can't work out what supposedly has a nil value that is triggering this error?
As I understand it this means something is blank that can't be
No , This means you need to make sure outlet
mealNameLabel.text = "Default Text" // here mealNameLabel is nil
is connected to the label in IB

how to add textfield delegate in swift

I need to add delegate to textfields; my understanding is it can be done two ways:
we go to file and viewController.swift and under class, after UIviewcontroller we add comma and then type UITextFieldDelegate .
and then u under viewDidLoad we add method and function
when on storyboard we click and drag textfield to small icon on top of view that says view controller and pick delegate
Do they both work the same? or there is difference if we do one way or the other?
and what you do if you have more than one textfields, I have 10 textfields and have 7 functions and buttons, I need to do this so I can disable button if my textfield is empty for that button.
There is no difference, as far as I know. Choose what you like more.
In first case you also need to make #IBOutlet for your UITextField(click and drag UITextField from UIStoryboard to your UIViewController code) and after that make UIViewController delegate of UITextField
For example:
import UIKit
class MyViewController: UIViewController, UITextFieldDelegate
{
#IBOutlet weak var myTextField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
myTextField.delegate = self
}
}

Enable user interaction of a button SWIFT

OK, so lets assume the button created below is greyed out and user interaction disabled.
How do I enable the button from anywhere else.
I know how to disable the button from inside the button function, sender.enabled = false, but I don't want to disable it from there.
I want to re-enable the user interaction from outside the button function.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func loadButton(sender: UIButton) {
//i wan to enable interaction of this button via override func and NSUserDefaults
}
}
In iOS and OS X development you have so-called outlets that are variables pointing to UI elements. You can read more about them here.
To declare an outlet, you prefix your variable with #IBOutlet like so:
#IBOutlet weak var button: UIButton!
and then you need to connect your outlet to the button in your xib file. That can be done in several ways, but if you have declared a variable like the above, you can:
go to your storyboard
in the document outline hold down the control button
while holding down the control button, you drag from your files owner or ViewController to the UIButton you'd like to connect to
select the outlet you'd like to connect to (button in this case)
As shown here
Once that is in place, you are free to use enable your button (and much more) in your code, for instance:
func viewDidLoad() {
super.viewDidLoad()
button.enabled = false
}
You can read more about IBOutlets here
And here is another way to connect outlets (this is how I prefer to connect outlets actually, you define and connect in one go)
Hope that helps