Working with delegates and encapsulation/ARC - ios

So I created a delegate in the following way:
class MessengerTableViewController: UITableViewController, MessengerTableViewControllerDelegate, UITableViewDataSource, UITextFieldDelegate {
//..Insert Various functions Here..
func messengerScrollToBottom() {
self.tableView.setContentOffset(CGPointMake(0, CGFLOAT_MAX), animated: true)
}
}
The protocol is :
protocol MessengerTableViewControllerDelegate {
func messengerScrollToBottom()
}
And the class using messengerScrollToBottom() is the superView :
class ContainerViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var containerViewController : UIView
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
self.msgDelegate = MessengerTableViewController(coder: nil)
}
func keyboardWillShow(aNotification: NSNotification) {
self.msgDelegate!.messengerScrollToBottom()
}
}
This will not work because within the ContainerViewController init() function, msgDelegate is not assigned to the proper MessageTableViewController. It does not point to the MessengerTableViewController that is already created by the storyboard in memory. Therefore the code executes fine, however I see no change in the tableView onscreen. My question is, how can I modify this code to have it occur as intended?
Here is an image of my storyboard:
http://imgur.com/z09dapF
Help would be appreciated!
EDIT:
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController ].
if segue?.identifier == "tableView" {
let child = segue!.destinationViewController as? MessengerTableViewController
self.msgDelegate = child
}
// Pass the selected object to the new view controller.
}
I implemented the code above and now it works..except with one catch. The tableView is blank upon executing messengerScrollToBottom() . Any know why?
Second edit: Turns out CGFLOAT_MAX was the problem, thanks.

You need to set the delegate when you segue to the MessengerTableViewController. Since you're using a segue, you should do that in prepareForSegue. Get a reference to the MessengerTableViewController with segue.destinationViewController.
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
let messengerTVC: MessengerTableViewController = segue.destinationViewController as ViewController
self.msgDelegate = messengerTVC;
}

Maybe try declaring a MessageTableViewController property in your header file, and then bind it to the MessageTableViewController in your storyboard? Then in the init() you could assign that property to be the object's delegate?

Related

Using button in another view controller

This question might be asked already about hiding buttons, but I was wondering if I could just click a button which would affect the variables in another view controller. For example, I have firstViewController and endViewController. There's a button in endViewController that the user presses which should change a variable in the firstViewController. Is there a way to access the endViewController button from the firstViewController?
Edit
I haven't tried much so far except control clicking the endViewController button into the firstViewController (which didn't work).
class firstViewController: UIViewController {
#IBAction func nextButton(_ sender: Any) { //button that sits in endViewController
}
}
You can use the DELEGATE PATTERN to pass data back:
Here's a little help on delegates between two view controllers:
Step 1: Make a protocol in the UIViewController that you will be removing/will be sending the data.
protocol FooTwoViewControllerDelegate:class {
func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}
Step2: Declare the delegate in the sending class (i.e. UIViewcontroller)
class FooTwoViewController: UIViewController {
weak var delegate: FooTwoViewControllerDelegate?
[snip...]
}
Step3: Use the delegate in a class method to send the data to the receiving method, which is any method that adopts the protocol.
#IBAction func saveColor(_ sender: UIBarButtonItem) {
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}
Step 4: Adopt the protocol in the receiving class
class ViewController: UIViewController, FooTwoViewControllerDelegate {
Step 5: Implement the delegate method
func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " + text
controller.navigationController.popViewController(animated: true)
}
Step 6: Set the delegate in the prepareForSegue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! FooTwoViewController
vc.colorString = colorLabel.text
vc.delegate = self
}
}
And that should work. This is of course just code fragments, but should give you the idea. For a long explanation of this code you can go over to my blog entry here:
segues and delegates
If you are interested in what's going on under the hood with a delegate I did write on that here:
under the hood with delegates
original answer
First View Controller
The code for the First View Controller is
import UIKit
class FirstViewController: UIViewController, DataEnteredDelegate {
#IBOutlet weak var label: UILabel!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showSecondViewController" {
let secondViewController = segue.destinationViewController as! SecondViewController
secondViewController.delegate = self
}
}
func userDidEnterInformation(info: String) {
label.text = info
}
}
Note the use of our custom DataEnteredDelegate protocol.
Second View Controller and Protocol
The code for the second view controller is
import UIKit
// protocol used for sending data back
protocol DataEnteredDelegate: class {
func userDidEnterInformation(info: String)
}
class SecondViewController: UIViewController {
// making this a weak variable so that it won't create a strong reference cycle
weak var delegate: DataEnteredDelegate? = nil
#IBOutlet weak var textField: UITextField!
#IBAction func sendTextBackButton(sender: UIButton) {
// call this method on whichever class implements our delegate protocol
delegate?.userDidEnterInformation(textField.text!)
// go back to the previous view controller
self.navigationController?.popViewControllerAnimated(true)
}
}
Note that the protocol is outside of the View Controller class.
That's it. Running the app now you should be able to send data back from the second view controller to the first.
Original post: https://stackoverflow.com/a/33229483/13783496
There are 2 methods:
You can create a segue from button in endviewcontroller to firstviewcontroller in storyboard. You can configure the func prepare(for segue: UIStoryboardSegue, sender: Any?) for it.
let endVC = endViewcontroller()
endVC.color = "blue"
You can keep the variable whose value needs to be changed as static datatype.
On the click action of button, you can access variable as,
EndViewController.color = "Red".
Kindly use static variables only if you want other Viewcontrollers to access it directly.

How to trigger action on embedded ContainerViewController from ViewController and how to do it inverse?

does anyone know how to pass an action from ViewController to its ContainerViewController. I try to hide the container view by an action that is triggered by itself. The ContainerViewController is embedded in the container view.
ViewController:
#IBOutlet weak var ChoseLanguageContainer: UIView!
**ContainerViewController:**
#IBAction func action(_ sender: Any) {
ViewController().containerView.isHidden = true
} //I know this does not work
I had the similar requirement, I created my own delegate methods which were implemented in ContainerViewController.
protocol ContainerViewControllerDelegate :class{
func notifyItemChange(any params you need to pass.)
}
In my container ViewController, I created a variable for delegate.
var changeContainerDelegate :ContainerViewControllerDelegate?
In my parent View Controller which contains the container, I did the following.
To get the instance of view controller which is embedded in the container.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let containerViewController = segue.destination as? ContainerViewController{
containerViewController.changeContainerDelegate = self
}
Create IBOutlet of container view in your view controller.
Conform to this protocol and write the implementation in View controller.
func changeContainerVC(containerVCName : String ,dataToBePassed:[AnyObject]?) {
containerView.isHidden = true
}
In the button action inside the ContainerViewController call the delegate like :
changeContainerDelegate?.notifyItemChange()
This works for me. Hope helps ou too!
In your code:
ViewController().containerView.isHidden = true
You are making a new instance of the ViewController and using it to hide the containerView. This won't work. Instead you need to hide the containerView of the current instance of ViewController, i.e self.
Here is the code you can try:
class ViewController: UIViewController
{
#IBOutlet weak var containerView: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
}
#IBAction func hideContainerView(_ sender: UIButton)
{
self.containerView.isHidden = true
}
}
View Hierarchy:
Let me know if you face any other issue regarding this.

Prepare for segue not getting called in UITabbarController

I have gone through all the other posts about this topic but they don't seem to help me.
I have a UITabBarController that is launching two tabs. I want to pass data collected in tab1 to the UITabBar ViewController. I am trying to use delegete protocol for this but I am having trouble setting the delegate variable in the sending ViewController. The prepare for segue never gets called. I cannot even cycle through the viewcontrollers of the tabs inside the ViewDidLoad() of the Tabbar controller as they are not created yet and so nil.
I have used delegates before and it seems rather straightforward. Does it matter that I am using it in a Tabbar?
When I run the code the viewDidLoad() in TabBarViewController is called but not the preparefor segue.
The IBAction donePressed in the MeViewController is called but the delegate is not called as its not set.
Here is the code --
protocol DetailsDelegate: class {
func myDetailsGathered( myDetails: MyDetails )
}
/// RECEIVING VIEW CONTROLLER
class TabBarViewController: UITabBarController, DetailsDelegate
{
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
print("prepare for segue called\n");
if let destinationViewController = segue.destination as? MeViewController
{
destinationViewController.delegate = self
}
}
override func viewDidLoad()
{
print("ViewDidLoad Called \n")
}
func myDetailsGathered(myDetails: MyDetails)
{
self.myDetails = myDetails
print("My details gathered \n")
}
}
---------------
/// SENDING VIEW CONTROLLER
class MeViewController: UIViewController
{
weak var delegate: DetailsDelegate?
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
// I have UIButton in the view and this is invoked when its pressed.
#IBAction func donePressed(_ sender: Any)
{
var infoToPass = MyDetails()
print("looks like we are done")
delegate?.myDetailsGathered(infoToPass: myDetails)
}
}
prepareForSegue is called when you perform a segue. Which you don´t do and that´s why it does not get called.
A segue defines a transition between two view controllers in your
app’s storyboard file.
You should use a singleton class to store variables and access them between different controllers. You declare one like this:
class Singleton {
static let sharedInstance = Singleton()
var name = ""
}
Assign to Singleton:
Singleton.sharedInstance.name = "Some name"
To read from it from whatever controller:
let name = Singleton.sharedInstance.name
First of all, why do you want your tabbarController to receive some info/data though?
The prepare for segue never gets called.
prepareForSegue method will be invoked right after the performSegue. So where's your performSegue method? Or are you sure that that kind of segue going to MeViewController is being performed?
One more option you have is to use NotificationCenter.

how can I pass data from one container to another, both embedded in the same uiviewcontroller in swift?

I have a parent UIViewController and it has two different view containers - each of them has embedded UIViewController inside. It looks somehow like this:
I want to change the label on the right container when user presses the button stored on the left one.
So far I was able to do it while having a button placed in a parent view controller, then I was just using a protocol:
in my parent component I had:
class ParentController: UIViewController {
var delegateEmbedded:HandleEmbedded?
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "segueToFirstEmbeddedController"){
if let embeddedView = segue.destinationViewController as? EmbeddedContainer {
self.delegateEmbedded = embeddedView
}
}
in my container-embedded UIViewController I had:
protocol HandleEmbedded: class {
func setName(label: String)
}
class EmbeddedContainer: UITableViewController, HandleYourChat{
func setName(label: String){
print("setting label to \(label)")
}
}
Situation above works when I have the button placed in a parent controller and want to change the label inside a container. But what happens and how should I pass the data when the button is also embedded, but in a different container than the label?
Do I have to pass the data through the parent controller? What's the best way for doing so?
To pass data from one embedded ViewController to another embedded ViewController, have the parent handle the transfer. Here I have provided a complete example with three ViewControllers and a single StringTaker protocol. Both the main ViewController and the LabelViewController implement this protocol. The main ViewController takes a string from the ButtonViewController and passes it on to the embedded LabelViewController.
ViewController.swift
import UIKit
protocol StringTaker: class {
func takeString(string: String)
}
class ViewController: UIViewController, StringTaker {
weak var stringTaker: StringTaker?
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EmbedButtonViewController" {
let dvc = segue.destinationViewController as! ButtonViewController
dvc.delegate = self
} else if segue.identifier == "EmbedLabelViewController" {
let dvc = segue.destinationViewController as! LabelViewController
stringTaker = dvc
}
}
// Receive the string from the ButtonViewController
func takeString(string: String) {
// Pass it to the LabelViewController
stringTaker?.takeString(string)
}
}
ButtonViewController.swift
import UIKit
class ButtonViewController: UIViewController {
weak var delegate: StringTaker?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func generateString(sender: UIButton) {
let cities = ["Boston", "Paris", "Sydney", "Mumbai", "Lima"]
// Pick a random city
let city = cities[Int(arc4random_uniform(UInt32(cities.count)))]
// Pass the string to the delegate
delegate?.takeString(city)
}
}
LabelViewController.swift
import UIKit
class LabelViewController: UIViewController, StringTaker {
#IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func takeString(string: String) {
myLabel.text = string
}
}
Things to note:
The LabelViewController and the ButtonViewController know nothing about the ViewController that uses them. This makes it easier to reuse them. You could embed them in another viewController and as long as you properly implement the StringTaker protocol and set up the delegate, everything works.
The key to hooking this up in in naming the embed segues and then properly setting up the delegates in prepareForSegue. The segues can be found in the Document Outline view once the Container is added to the ViewController.

Swift 2 - Method not being called through delegate

Hello learning swift and am stuck with calling a method through delegate. Checked multiple answers with similar issues and have tried the solutions but have not been able to successfully apply them to my own situation however I am close.
I have a delegator class named ViewController that holds a variable I would like to change. I have another view called MoodScroll which serves as the delegate. Moodscroll has a button being used to change the value for the variable in ViewController.
ViewController :
class ViewController: UIViewController, AVAudioPlayerDelegate, MoodScrollDelegate {
var alarmSoundType: String?
func acceptData(data: String?) {
alarmSoundType = "\(data)"
print(data)
}
}
MoodScroll :
protocol MoodScrollDelegate {
func acceptData(data: String?)
}
import UIKit
class MoodScroll: UIViewController {
#IBAction func WTF(sender: AnyObject) {
self.delegate?.acceptData("hello")
print("function called")
}
}
The IBAction calls fine as it prints "function called" in the console however it doesn't pass the value to ViewController as alarmSoundType remains nil and also the print command is not called in ViewController as well.
It seems you still have some confusion about delegation : if ViewController conforms to MoodScrollDelegate protocol, then your ViewController object will be the delegate, not the MoodScroll object.
Where do you set the delegate property of your MoodScroll object ?
If this object is created programmatically from your ViewController object, you should set it after initialization :
myMoodScrollObject.delegate = self
Is the object is created using Interface Builder, you can either use an outlet variable for delegate, or set it in prepareForSegue:sender of your ViewController class :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let scroll = segue.destinationViewController as? MoodScroll{
scroll.delegate = self
}
}
One picky note: the way you have described your problem, it's actually ViewController what you should call the delegate of MoodScroll. Most likely you're probably forgetting to set the delegate property of MoodScroll.
I don't know how these two view controllers relate to each other in your code, but very often you would set the delegate property in the prepareForSegue method of ViewController, for example:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SegueToMoodScroll" {
let moodScrollController = segue.destinationViewController as! MoodScroll
moodScrollController.delegate = self
}
}

Resources