How do you use Interface builder with Swift? - interface-builder

When hooking Swift code up to a Storyboard, how do you add the IBAction and IBOutlet tags?

Add IBAction and IBOutlet attributes to variables and functions so they can be visible in Interface builder.
class ViewController: UIViewController {
#IBOutlet var label: UILabel?
#IBAction func doTap(x:UIButton) {
println("Tapped: \(x)")
}
}

Below code shows IBOutlet and IBAction format in Swift :
class MyViewController: UIViewController {
#IBOutlet weak var btnSomeButton: UIButton?
#IBOutlet weak var lblLabelItem: UILabel?
#IBAction func btnSomeButtonClicked(sender: UIButton) {
...
}
}
You can bind them same way as done in Objective-C.

Just use old ctrl + drag technique which was popular in Xcode5 and everything works fine.

I would agree more with Jayprakash than the upvoted first answer. The only thing I would correct is the marking of the IBOutlets as implicitly unwrapped with the ! The first answer used to be correct, but several changes were made in Swift and how it interacts with IB in the latest release. In Swift, IBOutlets no longer have any implicit behavior or magic--they are simply annotations for IB. As of the date of this response, the following code is correct:
// How to specify an the equivalent of IBOutletCollection in Swift
#IBOutlet var fields: [UITextField]!
// How to specify a standard IBOutlet
#IBOutlet weak var button: UIButton!
// How to specify an IBAction
#IBAction func buttonWasPressed(sender: UIButton) { ... }

While creating a project, you should have selected the storyboard, so that you can add your IBOutlet's directly in the story board.
The Below code gives you a idea of how to add IBOutlet to the UILabel
class ViewController: UIViewController {
#IBOutlet var label : UILabel
}

Related

Drag - connect an UISwitch to an IBOutlet on a delegate class

My goal is to enable/disable the editing of a UITextField with a UISwitch using delegates. This is the delegate class:
import Foundation
import UIKit
class SwitchedTextFieldDelegate : NSObject, UITextFieldDelegate{
#IBOutlet weak var switchText : UISwitch!
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
//Here I intended to read the UISwitch state
print("Can't touch this")
return false
}
}
I've tried to drag-connect the IBOutlet to the storyboard, but it is not possible. I can do it on the main view controller, which inherits UIViewController. I've already learned that multiple inheritance is not possible in Swift. How would you solve this? I'll try using an IBAction instead.
In your main view controller drag IBOutlet of a UITextField and UISwitch. Then confirm the UITextField Delegate. Now implement the UITextField Delegate method Like this:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if switchText.on{
return true
}else{
return false
}
}
For better understanding I have shared my ViewController screen shot.Here FirstViewController is just like your MainViewController. Hope this will help you.

Dismissing View Controller for osx

I'm trying to learn swift code for mac OSX but there isn't much tutorials for it as ios. and i have been struggling already with closing or dismissing the view controller when i launch through a button another connected view controller
class ViewController: NSViewController {
#IBOutlet weak var username: NSTextField!
#IBOutlet weak var password: NSTextField!
#IBAction func login(sender: AnyObject) {
}
#IBAction func signUp(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
I tried to add [self dismissModalViewControllerAnimated:YES]; to dismiss it but it doesn't work it only shows errors. if anybody could point me to somewhere i can get more information or what i'm doing wrong?
Use
dismissViewController(self)
to dismiss the presented view controller.
About dismissViewController: from the NSViewController docs:
Dismisses a presented view controller, using the same animator that presented it.
and
In OS X, this is the universal way to dismiss a view controller, no matter how it was presented.

Access an IBOutlet from another class in Swift

I'm new to Swift and Mac App.
So I'm writing an Mac App today and I still confuse how to access an IBOutlet from another class after searching a lot.
I'm using StoryBoard and there are two NSTextField path mirror in my ViewController.
I have created a custom class Path.swift for the first NSTextField path to know when the text in path has changed.
class Path: NSTextField, NSTextFieldDelegate
{
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
// Drawing code here.
self.delegate = self
}
var current = ""
override func controlTextDidChange(obj: NSNotification)
{
current = self.stringValue
println("Current is \(current)")
}
}
And there are two outlets defined in ViewController.swift
class ViewController: NSViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
#IBOutlet weak var path: NSTextField!
#IBOutlet weak var mirror: NSTextField!
}
And when user type something in the first NSTextField path, I want the second NSTextField mirror shows the same string as path.
I tried to use ViewController().mirror.stringValue = current, but I got fatal error: unexpectedly found nil while unwrapping an Optional value
After googling a lot, I knew that I have created a new instance of ViewController instead of accessing the current existing instance of ViewController.
So my question is how I can access the IBOutlet in ViewController.swift from Path.swift class (how to access the current existing instance of ViewController).
Any help will be greatly appreciated.
Thanks in advance.

Pass continuous colorwell data to second view controller

I have the following situation:
two ViewControllers each containing a box that is to be colored to a color picked from a color well in ViewController
The colorwell is set as continuous in order to see the changes reflected immediately
I am looking for a way to continuously pass the color well value on to the SecondViewController and on to a callback method that will color a box in the SecondViewController.
I found that the prepareForSegue method is commonly used to pass data between view controllers, this however only occurs once during the transition and not continuously.
Can someone point me out in the right direction? Googled for hours but I got really stuck with this.
Thanks.
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var box: NSBox!
#IBOutlet weak var well: NSColorWell!
#IBAction func well(sender: AnyObject) {
box.fillColor = well.color
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
let second = segue.destinationController as! SecondViewController
second.representedObject = well.color
}
}
import Cocoa
class SecondViewController: NSViewController {
#IBOutlet weak var box: NSBox!
override func viewWillAppear() {
// Note that box.fillColor requires box type to be custom
box.fillColor = self.representedObject as! NSColor
}
}
The prepareForSegue method is a chance to create links between two view controllers. It's pretty common for the source view controller to set itself up as the delegate of the destination view controller. It's also possible for the source view controller to save a reference to the destination view controller for future reference.
If you define a protocol with a method like
func colorValueHasChanged(newColor: NSColor)
Then you can use it in the IBAction for your color well to pass information about changes in the color well from one view controller to the other.

swift error exc_bad_access loading image using iboutlet

I'm new in iOS-programming. I tried the following. I created a custom class for a button (source founded on internet) like.
class CustomButton : UIButton {
var myAlternateButton:Array<CustomButton>?
var downStateImage:String? = "radiobutton_down"{
didSet{
if downStateImage != nil {
self.setImage(UIImage(named: downStateImage!), forState: UIControlState.Selected)
}
}
}
Now when i try to use the class in my TableViewController I get the error mentioned above
class SettingsTableViewController: UITableViewController {
#IBOutlet var testButton: CustomButton?
#IBOutlet var excelButton: CustomButton?
override func viewDidLoad() {
super.viewDidLoad()
testButton?.downStateImage = "radiobutton_down" -->xc_bad_access
why I can not set the property. Do I have to initialize the class separately or where is my error? Perhaps anyone can help me! Thanks,
arnold
Have you linked your outlet correctly with your UIButton on your interface builder? Be sure to set your custom class name on your custom view too, like so:
Also, if you're setting views using the IBOutlet system I would recommend defining them like this instead if the views are always present:
#IBOutlet weak var testButton: CustomButton!
#IBOutlet weak var excelButton: CustomButton!

Resources