I have not implemented UIViewController because I have already inherited from another class, and it gives the error that present is not a member of this class
func shareAppLink() {
let name = "http://aijaz.com"
let items = [name] as [Any]
let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
present(ac, animated: true)
}
You can also use Respoder Chain to get the parent view controller for a view
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
And declare your shareAppLink function like
func shareAppLink(sender : UIView) {
let name = "http://aijaz.com"
let items = [name] as [Any]
let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
sender.parentViewController(ac, animated: true)
}
then in didSelectRowAt, you can call it as:
self.shareAppLink(sender : cell)
present(_:animated:completion:) is a method of UIViewController, so it must be called on some type of UIViewController.
If your class is initially created by a view controller, then you could try passing in a reference using the delegation pattern:
Delegation is a simple and powerful pattern in which one object in a
program acts on behalf of, or in coordination with, another object.
The delegating object keeps a reference to the other object—the
delegate—and at the appropriate time sends a message to it. The
message informs the delegate of an event that the delegating object is
about to handle or has just handled.
If you created a protocol for your custom class something like this:
protocol MyClassDelegate {
func shareAppLink()
}
Then you could conform to that protocol in your View Controller and call the method something like this: delegate.shareAppLink()
You have to inherit UIViewController subclass or UIViewController class. By doing that an error should be resolved.
Related
In a tutorial for using UIPageViewController, there's a code that goes like this:
if self == parent.pages.first {
self.label_Back.isUserInteractionEnabled = false
}
Which basically checks if the self is the first controller stack. How does this work?
And also, if we have multiple instances of a controller class in pages array of UIViewController, will doing the firstIndex thing like below work?
/**
Notifies '_tutorialDelegate' that the current page index was updated.
*/
private func notifyTutorialDelegateOfNewIndex() {
if let firstViewController = viewControllers?.first,
let index = self.pages.firstIndex(of: firstViewController) {
tutorialDelegate?.tutorialPageViewController(tutorialPageViewController: self, didUpdatePageIndex: index)
}
}
if self == parent.pages.first
These are Cocoa (Objective-C) objects — UIViewController, descended from NSObject:
Swift == on an Objective-C object in the absence of an override calls isEqual:, inherited from NSObject.
For an NSObject, in the absence of an override, isEqual: defaults to object identity.
So this is just like Swift ===, i.e. it is true just in case these are identically the same view controller object.
Is there a way to avoid open variables when using segues (or not segues)?
Everybody saw code like this:
if segue.identifier == ListViewController.className()
{
guard let indexPath = tableView.indexPathForSelectedRow else { return }
let destinationVC = segue.destination as? ListViewController
var data: CategoryModel
data = filteredData[indexPath.row]
destinationVC?.passedData = data
}
}
But in ListViewController now we have a var that open for access.
class ListViewController: UIViewController
{
//MARK: - DataSource
var passedData: CategoryModel?
Maybe exist way to avoid this?
I was thinking about dependency injection with init(data: data), but how to initiate this vc right?
Edited.
Using segue it's not a main goal. Main is to make var private. If there exist nice way to not to use segues and push data private I will glad to know.
I was trying to use init() and navigationController?.pushViewController(ListViewController(data: data), animated: true)
but
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on line:
self.tableView.register(ListTableViewCell.nib(), forCellReuseIdentifier: ListTableViewCell.identifier())
You can't actually make Interface builder use a custom init for your view controller, it will always use init?(coder:).
So the easiest way to pass data to your view controller is to use a non-private property.
But if you really don't want to use an internal or public var you can always try something with a Singleton or Notifications but I don't think it would be wise
You could do it like so
class ListViewController {
private var passedData: CategoryModel?
private init () {
}
public convenience init (passedData: CategoryModel?) {
self.init()
self.passedData = passedData
}
}
And in tableView(_:didSelectRowAt:) of your initial table view controller:
let data: CategoryModel = filteredData[indexPath.row]
let destinationVC = ListViewController(passedData: data)
self.present(destinationVC, animated: true, completion: nil)
I am trying to emulate the iOS contacts segueing between two view controllers.
I have a simple Person class given by:
class Person {
var name = ""
}
and a UIViewController that contains an array of Person, which is embedded in a UINavigationController:
class PeopleViewController: UIViewController {
var people = [Person]()
var selectedPerson: Person?
switch segueIdentifier(for: segue) {
case .showPerson:
guard let vc = segue.destination as? PersonViewController else { fatalError("!") }
vc.person = selectedPerson
}
}
This controller uses a Show segue to PersonViewController to display the selectedPerson:
class PersonViewController: UIViewController {
var person: Person!
}
PeopleViewController can also add a new Person to the array of Person. The NewPersonViewController is presented modally, however:
class NewPersonViewController: UIViewController {
var person: Person?
}
If a new Person is added, I want NewPersonViewController to dismiss but show the new Person in the PersonViewController that is part of the navigation stack. My best guess for doing this is:
extension NewPersonViewController {
func addNewPerson() {
weak var pvc = self.presentingViewController as! UINavigationController
if let cvc = pvc?.childViewControllers.first as? PeopleViewController {
self.dismiss(animated: false, completion: {
cvc.selectedPerson = self.person
cvc.performSegue(withIdentifier: .showPerson, sender: nil)
}
}
}
}
However, (1) I'm not too happy about forcing the downcast to UINavigationController as I would have expected self.presentingViewController to be of type PeopleViewController? And (2), is there a memory leak in the closure as I've used weak var pvc = self.presentingViewController for pvc but not for cvc? Or, finally (3) is there a better way of doing this?
Many thanks for any help, suggestions etc.
(1) I'm not too happy about forcing the downcast to UINavigationController as I would have expected self.presentingViewController to be of type PeopleViewController?
There is nothing wrong in downcasting. I would definitely remove force unwrapping.
(2), is there a memory leak in the closure as I've used weak var pvc = self.presentingViewController for pvc but not for cvc?
I think, there is none.
(3) is there a better way of doing this?
You can present newly added contact from NewContactVC. When you about to dismiss, call dismiss on presentingVC.
// NewPersonViewController.swift
func addNewPerson() {
// New person is added
// Show PeopleViewController modally
}
Note: Using presentingViewController this way will dismiss top two/one Modal(s). You will see only top view controller getting dismissed.
If you can't determine how many modals going to be, you should look-into different solution or possibly redesigning navigation flow.
// PeopleViewController.swift
func dismiss() {
if let presentingVC = self.presentingViewController?.presentingViewController {
presentingVC.dismiss(animated: true, completion: nil)
} else {
self.dismiss(animated: true, completion: nil)
}
}
The situation: when I press a button in rentViewController, it pops up a tableviewcontroller. If a specific cell has been pressed, it sends data to rentViewController. In order to send data from one view controller to another I needed the code
let rentViewController : RentViewController = self.presentingViewController as! RentViewController <- here is where the error shows up
so that tableviewcontroller could get access to the variables and functions from rentviewcontroller. I'm using
self.dismiss(animated: true, completion: nil)
to get out of the tableviewcontroller and back to the rentviewcontroller. However, it gives me an error "Could not cast value of type 'UITabBarController' to 'RentViewController'". I did some research and I think it's according to the orders of my view controllers but I'm not sure how to change it in a way that it works. My initial view is 'TabBarController' and the order after that is 'NavigationController' -> 'RentViewController' -> 'TableViewController'. If you have questions feel free to ask I can provide you more information.
Your viewController is being presented from UITabBarController. With approach you are using I believe you can access it like this (where index is index in UITabBarController of your UINavigationController containing RentVC):
if let tab = self.presentingViewController as? UITabBarController,
let nav = tab.viewControllers?[index] as? UINavigationController,
let rentViewController = nav.viewControllers.first as? RentViewController {
rentViewController.data = data
}
However, I would suggest using a delegate or callback block to pass data in this occassion.
For delegate approach, first create protocol:
protocol PassDataDelegate:class {
func passData(data:YourType)
}
Then in TableViewController:
class TableViewController: UIViewController {
weak var delegate: PassDataDelegate?
}
And in RentViewController:
extension RentViewController: PassDataDelegate {
func passData(data:YourType) {
//use data to suit your needs
}
}
Before presenting TableViewController, in RentViewController, set its delegate:
tableViewController.delegate
present(tableViewController, animated: true)
And finally, inside TableViewController, before dismissing, call delegate's method to pass data:
delegate?.passData(data: <<someData>>)
I have two view controllers and I have this code to navigate between the two views
ViewController:
func goToSecondViewController() {
let aa = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.navigationController.pushViewController(aa, animated: true)
}
/
SecondViewController:
func goToFirstViewController() {
self.navigationController.popToRootViewControllerAnimated(true)
}
How to send some data to the first view before popping it ?
If A is a view controller with the following declaration:
class A : UIViewController {
var data: String!
}
Then, whenever you have an instance of A, you can just set the data property directly:
let a = A() // assuming you've defined the init method
a.data = "hello"
Edit
If you want to send data before popping, you'd do something like:
func goToFirstViewController() {
let a = self.navigationController.viewControllers.first as! A
a.data = "data"
self.navigationController.popToRootViewControllerAnimated(true)
}
(haven't compiled the above)