ios


How to use delegates properly in Swift?


I read a lot about the delegates but in practice I cannot use it properly.
Description: I have A: UIViewController, B: UIView, C: UIViewController. I want to run segue from A: UIViewController to the C: UIViewController from the inside of B: UIView.
I've tried:
protocol SegueDelegate {
func runSegue(identifier: String)
}
class B: UIView { ... }
where in my A: UIViewController:
override func viewDidLoad() {
B().delegate = self
}
func runSegue(identifier: String) {
self.performSegueWithIdentifier(identifier, sender: self)
}
and trying to call it via:
#IBAction func send(sender: AnyObject) {
let a: SegueDelegate? = nil
a!.runSegue("goToMainPage")
}
but I'm sure that I do not use it properly. Can anyone help me with it? I do not want just an answer. Please describe me it concept shortly
Delegates are just a Design Pattern that you can use in a number of ways. You can look at the Apple Frameworks to see how and where to use delegates as examples. A table view delegate is probably the best known delegate in UIKit.
Delegates serve as a callback mechanism for code to communicate with an instance of an unknown class without knowing more than that that instance will respond to the methods of the delegate protocol.
An alternative to a delegate is to use a closure (what we used to call a block in Objective-C). When to use one vs. the other is a matter of taste. There are a couple of rules of thumb, like for instance outlined here.
What you are doing is, IMO, the proper way to use delegates. You separate the view functionality from the View Controller's functionalities via a delegate, and so the contract for your view is clear: the user needs to respond to the delegate method.
Your code works and is correct. I made a quick implementation here: https://github.com/kristofvanlandschoot/DelegateUsage/tree/master
The main difference from your example, and maybe that's the place where you made a mistake is the third part of your code where you should write something like:
#IBAction func send(sender: AnyObject) {
delegate?.runSegue("segueAB")
}
There are multiple errors in your code, for example:
Here you are creating a new B, and setting A as a delegate of that new instance, no the one you actually want
override func viewDidLoad() {
«B()».delegate = self
}
And here you are creating force unwrapping a nil value
#IBAction func send(sender: AnyObject) {
let a: SegueDelegate? = «nil»
«a!».runSegue("goToMainPage")
}
If what you want to do is tell A to perform a segue to C, from inside B, all you need to do is to call performSegueWithIdentifier on A
For example:
class B: UIView {
weak var referenceToA: UIViewController? = nil // set this somewhere
#IBAction func send(sender: AnyObject) {
guard let a = referenceToA else {
fatalError("you didn't set the reference to a view controller of class A")
}
a.performSegueWithIdentifier("goToMainPage", sender: self)
}
}

Related Links

Firing a UIButton instantly
Compile FFMPEG in iOS with bitcode mode
UITableViewCell's contents' alpha changes on its own
Ranging beacons in background
Accessibility Id's for GLKView
Manual UINavigationBar layout issue
What is the blur/translucency of the Tab Bar iOS
handlewatchkitextensionrequest not calling Async call in suspended state
Force lowercase - ios swift
AVAssetReader/AVAssetWriter preview of current frame
iOS Unit Testing: Class is implemented in both
pjsip Assertion failed: mod_tsx_layer.endpt==((void *)0)
How to declare a dictionary variable inside a swift class?
Swift, how to convert an existing uiview to uiscrollview?
UITextField Text Invisible Until Editing
How to trigger Core Bluetooth state preservation and restoration

Categories

HOME
f#
simulated-annealing
logstash
google-search
elf
orbeon
openshift-origin
android-activity
robotframework
haskell-stack
fpdf
plotly
add-in
apache-spark-sql
pie-chart
wavelet
avr
orchardcms-1.10
stackexchange-api
oracle11gr2
formio
multiprocessing
co
naturallyspeaking
epicorerp
number-formatting
jsplumb
python-responses
angular2-databinding
apache-commons-httpclient
seh
spring-websocket
blockui
phing
jetty-9
solid-principles
extjs4
azure-management-api
subscription
formatdatetime
phasset
android-calendar
ms-jet-ace
ssms-2012
notimplementedexception
libev
ietf-netconf
untagged
assembly-references
turnjs
ckcontainer
visual-build-professional
selenium2library
viewengine
training-data
interpreted-language
json4s
wt
voting
translucency
gevent-socketio
vraptor
android-menu
clearcase-remote-client
bson
asp.net-apicontroller
xsltforms
android-lru-cache
siblings
broadcom
datapump
firebird2.1
hla
git-gui
dynamic-usercontrols
pixelsense
ad-hoc-distribution
arden-syntax
zmodem
sticky-footer
ms-access-97
expressionvisitor
junitperf
closest
noaa
high-traffic
drupal-gmap
coords
gedcom
plumtree

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App