Passthrough clicks, events from Child View Controller to Parent View Controller - ios

I have some buttons in Child View Controller. I'd like a user to be able to click on these buttons, and, in case he clicks in other area, Parent View Controller to be able to process those clicks that Child View Controller doesn't work with.

You need to create protocols and delegates.
protocol Vc2Delegate : AnyObject {
func buttonPressed()
}
class Vc1 : UIViewController, Vc2Delegate {
func presentVC2() {
let vc2 = Vc2()
vc2.delegate = self
present(vc2)
}
func buttonPressed() {
// process vc2 button press in vc1
}
}
class Vc2 : UIViewConttoller {
// weak !!!!
weak var delegate : Vc2Delegate? = nil
func buttonInVc2Pressed() {
// call func in vc1 from vc2
delegate?.buttonPressed()
}
}
P.S. Sorry for formatting, was wrote from iPhone.

Related

Swift Protocol Third VC to First VC

I need to pass a String and Array from my Third ViewController to my First ViewController directly using protocol/delegate, I have no problem doing it from VC 2 to VC 1 but I'm having a hard time with this. Also after clicking a button in my VC3 I need to go back to VC 1 and update the VC UI how would I do that? Would that have to be in viewdidload?
This in Swift UIKit and Storyboard
You need two protocols, and your firstVC and SecondVC have to conform those. When pushing new ViewController you need to give the delegate of that ViewController to self. On your third VC, when you click the button you need to call your delegate and pass your data to that delegate method, then repeat the same for other.
For FirstVC
protocol FirstProtocol: AnyObject {
func firstFunction(data: String)
}
class FirstVC: UIViewController, FirstProtocol {
weak var delegate: FirstProtocol?
#IBAction func buttonClicked(_ sender: Any) {
let secondVC = SecondVC()
secondVC.delegate = self
navigationController?.pushViewController(secondVC, animated: true)
}
func firstFunction(data: String) {
navigationController?.popToRootViewController(animated: true)
print(data)
}
}
You handle your navigation from your root. For better experience you can use something like coordinator pattern to handle it.
protocol SecondProtocol: AnyObject {
func secondFunction(data: String)
}
class SecondVC: UIViewController, SecondProtocol {
weak var delegate: FirstProtocol?
#objc func buttonClicked() {
let thirdVC = ThirdVC()
thirdVC.delegate = self
navigationController?.pushViewController(thirdVC, animated: true)
}
func secondFunction(data: String) {
delegate?.firstFunction(data: data)
}
}
Second VC is something that you just need to pass parameters.
class ThirdVC: UIViewController {
weak var delegate: SecondProtocol?
#objc func buttonClicked() {
delegate?.secondFunction(data: "data") // PASS YOUR ARRAY AND STRING HERE
}
}
What you need is unwind segue. Unwind segue will act like segue, only backward, popping, in this case, VC2. You can read here for more information.
Updating data code would be put in a function similar to prepareToSegue() but for unwind segue in your VC1.
Example of the function inside VC1:
#IBAction func unwindToDestination(_ unwindSegue: UIStoryboardSegue) {
switch unwindSegue.identifier {
case SegueIdentifier.yourSegueIdentifier:
let sourceVC = unwindSegue.source as! SourceVC
dataToPass = sourceVC.dataToPass
reloadData()
default:
break
}
}
Here is a different approach that accomplishes what you described by performing a Present Modally segue directly from View Controller 3 to View Controller 1, and sharing the string and array values by way of override func prepare(for segue....
In Main.storyboard, I set up 3 View Controllers, and have segues from 1 to 2, 2 to 3, and 3 to 1. These are Action Segues directly from the buttons on each VC, which is why you won't see self.performSegue used inside any of the View Controller files. Here is the picture:
In the first view controller, variables are initialized (with nil values) that will hold a String and an Array (of type Int in the example, but it could be anything):
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var updatableTextLabel: UILabel!
var string: String?
var array: [Int]?
override func viewDidLoad() {
super.viewDidLoad()
// These will only not be nil if we came here from the third view controller after pressing the "Update First VC" button there.
// The values of these variables are set within the third View Controller's .prepare(for segue ...) method.
// As the segue is performed directly from VC 3 to VC 1, the second view controller is not involved at all, and no unwinding of segues is necessary.
if string != nil {
updatableTextLabel.text = string
}
if let a = array {
updatableTextLabel.text? += "\n\n\(a)"
}
}
}
The second view controller doesn't do anything except separate the first and third view controllers, so I didn't include its code.
The third view controller assigns the new values of the string and array inside prepare (this won't be done unless you press the middle button first, to demonstrate both possible outcomes in VC 1). This is where your string and array get passed directly from 3 to 1 (skipping 2 entirely).
import UIKit
class ThirdViewController: UIViewController {
var theString = "abcdefg"
var theArray = [1, 2, 3]
var passValuesToFirstVC = false
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func updateFirstVC(_ sender: UIButton) {
passValuesToFirstVC = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if passValuesToFirstVC && segue.identifier == "toFirst" {
// Cast segue.destination (which on its own has type UIViewController, the superclass to all your custom View Controllers) to the specific subclass that your first View Controller belongs to
let destinationVC = segue.destination as! FirstViewController
// When your first view controller loads, it will receive these values for the 'string' and 'array' variables. They replace the original 'nil' values these had in the FirstViewController definition.
destinationVC.string = theString
destinationVC.array = theArray
}
}
}
Note that there is an IBOutlet to the label on the first View Controller which contains the text to be updated.
After visiting the third view controller, pressing the "Update First VC Text" button, and then performing the segue back to the first, here is how it will look:
This doesn't address the part about protocols and delegates in your question (as I'm not sure how they're being used in your program, and other answers have already addressed that), but it illustrates the method of transferring variables directly from one View Controller to another without unwinding segues or using the UINavigationController.

Reuse navigation bar button

In my project I have UINavigationController with three embedded UIViewControllers. On the first one I add balanceLabel and refreshButton to navigation bar. When click on button first view controller send url request and show return value on label.
#IBAction func refreshButtonAction(_ sender: UIBarButtonItem) {
let operation = GetInfoOperation(...)
operation.completionBlock = { [weak self] in
DispatchQueue.main.async {
guard let balance = operation.output?.value?.balance else { return }
self?.balanceLabel.text = balance
let significantDigits = Int(Double(balance.toInt64!) * pow(10, -10))
}
}
queue.addOperation(operation)
}
How can I get the same behaviour on other ViewControllers without duplicate #IBAction func refreshButtonAction(_ sender: UIBarButtonItem) in each ViewController?
you can archive this by extension, using inheritance,
create the view controller you want with all the common feature you want and then instead of inheriting directly from UIViewController inherit from that base viewController
your base controller BaseViewController
class BaseViewController: UIViewController {
//all comman functionallity
//add your button here
}
class ChildOneViewController: BaseViewController {
//this class will get all the functionality from BaseViewController
//you can access the BaseViewController button here
//add function for ChildOneViewController
}
class ChildtwoViewController: BaseViewController {
//this class will get all the functionality from BaseViewController
//you can access the BaseViewController button here
//add function for ChildtwoViewController
}

Perform segue from sub-ViewController

At the moment I have a ViewController class containing a UIScrollView, within the scroll view I have another view controller, where I can currently receive gesture recognition. My goal is to be able to perform a segue to a different view controller, based on which subViewController I tap.
let scrollView = UIScrollView(frame: CGRect(x:0,y:0, width: self.view.frame.width, height:self.view.frame.height-106))
scrollView.delegate = self;
self.view.addSubview(scrollView);
let subView11 = subView(nibName: nil, bundle: nil);
subView1.view.frame = CGRect(x:0,y:0, width: self.view.frame.width, height: CGFloat(openReelHeight));
self.addChildViewController(subView1);
scrollView.addSubview(subView1.view);
subView.didMove(toParentViewController: self);
Then in the subView class I have a basic touch recognition function:
#IBAction func tapOnView(_ sender: UITapGestureRecognizer) {
//change main View controller
}
I would suggest letting the parent perform the segue. So you need a mechanism to let the child inform the parent that the button has been tapped. Here are two approaches:
The child view controller can define a protocol and then have its #IBAction for the button invoke that in the parent view controller.
protocol ChildViewControllerDelegate {
func child(_ child: ChildViewController, didTapButton button: Any)
}
class ChildViewController: UIViewController {
#IBAction func didTapButton(_ sender: Any) {
if let parent = parent as? ChildViewControllerDelegate {
parent.child(self, didTapButton: sender)
}
}
}
Clearly, the parent view controller needs to conform to that protocol:
extension ViewController: ChildViewControllerDelegate {
func child(_ child: ChildViewController, didTapButton button: Any) {
// now segue to whatever you want
}
}
You can alternatively follow an explicit protocol-delegate pattern, rather than relying upon the view controller containment relationships of the parent:
protocol ChildViewControllerDelegate: class {
func didTapButton(_ sender: Any)
}
class ChildViewController: UIViewController {
weak var delegate: ChildViewControllerDelegate?
#IBAction func didTapButton(_ sender: Any) {
delegate?.didTapButton(sender)
}
}
And then, when the parent adds the child, it would have to explicitly set the delegate:
let child = storyboard!.instantiateViewController(withIdentifier: "ChildViewController") as! ChildViewController
addChildViewController(child)
child.delegate = self
// add the child's view to your view hierarchy however appropriate for your app
child.didMove(toParentViewController: self)
And, of course, the parent again has to conform to this protocol:
extension ViewController: ChildViewControllerDelegate {
func didTapButton(_ sender: Any) {
// segue to next scene
}
}
Note, with both of these approaches, you can change your protocol's func to include whatever parameters you want (e.g. passing back contents of some UITextField or whatever). Likewise, you might use method names that make the functional intent of the child a little more explicit. I used somewhat generic method and protocol names because I don't know what the various children are doing.

Initial func in 1st view from 2nd view (swift)

I have a button on 2nd viewController, after pressing that button, I would like to dismiss the 2nd viewController and go back to the 1st view controller and immediately call a function that coded inside 1st ViewController swift file.
May I know how can I do that? By segue?
There are many way to do this one of the best way is using protocol and delegate.
You can create one protocol and extend that protocol in your ViewController1. Now create the delegate of protocol in ViewController2 and pass reference of that delegate in the ViewController1's prepareForSegue method.
First create one protocol like this
protocol PassdataDelegate {
func passData()
}
Now extend this protocol in ViewController1 like this and pass the reference of delegate in prepareForSegue method
class ViewController1 : UIViewController, PassdataDelegate {
func passData() {
//Here call your function
self.callMyFunction()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "SegueIdentifier") {
let destVC = segue.destinationViewController as! ViewController2
destVC.delegate = self
}
}
}
Now create the delegate object of protocolin ViewController2 like this
class ViewController2 : UIViewController {
var delegate: PassdataDelegate?
//Now call the method of this delegate in Button action
#IBAction func buttonClick(sender: UIButton) {
self.delegate.passData()
//Now dismiss the controller
}
}
Note: - Here i am passing stringbut you can pass any type of object that you have declare in your delegate method.
You can refer unwind segue.
class ViewController1 {
#IBAction func doSomeStuffAfterReload(segue: UIStoryboardSegue) {
// do whatever you need to do here.
}
}
On storyboard, from ViewController2 Ctrl+Drag from the button to the exit outlet and select doSomeStuffAfterReload.
You can see it in action here: https://spin.atomicobject.com/2014/10/25/ios-unwind-segues/
Happy coding^^

Delegation from ContainerView to parent ViewController

I have the following setup:
StartViewController has a ContainerView that contains ContainerViewController
I try to find a way to hidden an element in StartViewController after a task is performed in ContainerViewController.
For this I try to use delegation method like this:
StartViewController
class StartViewController: UIViewController, showBannerAdDelegate {
#IBOutlet weak var bannerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.hidden = false
}
func bannerAdHidden(status: Bool) {
bannerView.hidden = status
}
}
ContainerViewController
protocol showBannerAdDelegate: class {
func bannerAdHidden(status: Bool)
}
class ContainerViewController: UIViewController {
weak var delegate: showBannerAdDelegate! = nil
#IBAction func buttonPressed(sender: UIButton) {
delegate.bannerAdHidden(true)
}
}
If I presented the ContainerViewController I could do in prepareForSegue
let destination = segue.destinationViewController as! ContainerViewController
destination.delegate = self
But in this case both View Controller are always present.
What code should I add to the View Controller to make it work?
Thank you,
If one of the view controllers is inside a container view then it is loaded with an embed segue, which fires when the containing view controller is first loaded. The prepareForSegue method still gets called, so you can set up a delegate exactly as you've described. I always thought embed segues were a little odd (it's not really a segue, more like loading a child view controller) but that's how it works.

Resources