Communication between view controllers, not able to pass on the data to the outlet of second view controller - cocoa-touch

Two view controllers:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (sender as! cell1).name.text == "ww"{
let s = segue.destination as! DetailViewController
s.detail?.text = "wwwwwwwwwww"
}
}
I am new to coding. What I am trying here is to communicate between view controllers. For some reason, I am not able to show the wwwwwwwwwww in the label of the second view controller

At the prepare function the view hasn't been loaded yet from storyboard, so the outlets of the DetailViewController are still nil.
Create a public variable in the DetailViewController which will be available at prepare, then in the viewDidLoad method of DetailViewController you can set the label's text to be the content of that variable.
class DetailViewController: UIViewController {
var text: String?
override function viewDidLoad() {
super.viewDidLoad()
label.text = text
}
}
Then in your list viewcontroller set the text property of detail vc:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard (sender as! cell1).name.text == "ww",
let detailVc = segue.destination as? DetailViewController
else { return }
detailVc.text = "wwwwwwwwwww"
}

Related

Xib not showing up in view

I have a Xib file trying to set it up with my storyboard. Everything in the Xib file is fine, but for some reason, it's not showing. I imported a file from GitHub which is set to my Xib, it's in Objective-C and I set the bridging, no errors. But when I run it nothing shows its blank. Did I not set something in the View Controller? Everything is done programmatically and I just set the class in storyboard.
Screenshot of storyboard:
What the simulator gives me when I push to the ViewController:
This is what I'm supposed to see:
What I am trying to implement -
https://github.com/jberlana/JBCroppableView
My XIB class
import UIKit
class CropViewXIB: UIView {
#IBOutlet weak var ImageView: JBCroppableImageView!
#IBAction func SubAction(_ sender: Any) {
ImageView.removePoint()
}
#IBAction func AddAction(_ sender: Any) {
ImageView.addPoint()
}
#IBAction func UndoAction(_ sender: Any) {
ImageView.reverseCrop()
}
#IBAction func CropAction(_ sender: Any) {
ImageView.crop()
}
override init(frame: CGRect) {
super.init(frame: frame)
commomInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commomInit()
}
private func commomInit(){
Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)
self.addSubview(ImageView)
ImageView.frame = self.bounds
ImageView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
}
my view controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var cropView: CropViewXIB!
override func viewDidLoad() {
super.viewDidLoad()
}
}
The issue is that you didn't actually get the parent view for your UINib object.
Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)
The line above returns an [Any] in your case you aren't even using the view that it is returning. so the idea is to get the first object from it and cast it as UIView such as:
Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)?.first as? UIView
Personally this is how I interact with a Nib. I create a view property of type UIView that can be referred as the parent view for the nib, and all subviews get added to it instead of self.
Something like this:
final class SomeNibView: UIView {
public var view: UIView!
private func setup() { // called to the initializer
// grab the views from loadNibNamed
guard let _view = Bundle.main.loadNibNamed("name", owner: self, options: nil)?.first as? UIView else { return }
// set it to our view property
view = _view
// add this property to the nib subview aka self
addSubview(view)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
private func addMulitpleSubviews() {
// instead of doing self.addSubview(....) when it comes to add other subviews
// you'll do this view.addSubview(....)
}
}
Try to load xib using programming not using storyboard.
override func viewDidLoad()
{
super.viewDidLoad()
guard let yourXIB = Bundle.main.loadNibNamed("CropViewXIB", owner: self, options: nil)?.first as? CropViewXIB else { return}
self.view.addSubview(yourXIB)
}

How to populate array and view it's data at the same time - Swift - IOS9

I am trying to retrieve data from an online database, and I do that successfully; However, after retrieving the data from the database I would like to store it in an array and then populate a listview and a mapview with it's data, but there is a problem, I am able to load the data and store it and view it, however the problem is that everytime the app loads no information appears until I go to another scene and go back, because I am populating the array though the AppDelegate. However, if I populate it through the viewdidload I get duplicate items in my table view.
Here is my code:
Approach number 1, which leads to duplicates
StoreViewController.swift
class StoreViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, StoresModelProtocoal {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawForm()
setUpMap()
self.hideKeyboardWhenTappedAround()
getCurrentLocation()
let hideStoreDetail: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideStoreDetails))
Map.addGestureRecognizer(hideStoreDetail)
//Create a nib for the custom cell and use it in the table
let nib = UINib(nibName: "CustomStoreCell", bundle: nil)
StoresListTable.registerNib(nib, forCellReuseIdentifier: "customStoreCell")
let storesModel = StoresModel()
storesModel.delegate = self
storesModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
print("Items downloaded")
for item in items
{
if let s = item as? Store
{
print(s.Address)
Globals.unsortedStoresList += [s]
Map.addAnnotation(s.Annotation)
do_table_refresh()
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Globals.unsortedStoresList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomStoreCell = self.StoresListTable.dequeueReusableCellWithIdentifier("customStoreCell") as! CustomStoreCell
let s = Globals.unsortedStoresList[indexPath.row]
cell.loadItem(s.Name, StoreAddress: s.Address, StoreHoursOfOperation: s.HoursOfOperation, StoreDistanceFromCurrentLocation: String(s.DistanceFromCurrentLocation))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let s = Globals.unsortedStoresList[indexPath.row]
print(s.Name)
print(s.Address)
print(s.HoursOfOperation)
print(s.DistanceFromCurrentLocation)
//print("You selected cell #\(indexPath.row)!")
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.StoresListTable.reloadData()
return
})
}
I know this one duplicates the items because everytime the view is loaded it re-downloads all the data again; therefore, I tried looking for a better way and then I thought about doing the downloading process in my AppDelegate and then just write couple functions that take data from the array and display it, but the problem here is that the data would be displayed on the TableView right away without duplicates but it won't be displayed on the mapview at first run, instead I have to go to another scene and go back in order for the data to be displayed on the map.
Approach number 2
StoreViewController.swift
class StoreViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawForm()
setUpMap()
self.hideKeyboardWhenTappedAround()
getCurrentLocation()
let hideStoreDetail: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideStoreDetails))
Map.addGestureRecognizer(hideStoreDetail)
//Create a nib for the custom cell and use it in the table
let nib = UINib(nibName: "CustomStoreCell", bundle: nil)
StoresListTable.registerNib(nib, forCellReuseIdentifier: "customStoreCell")
loadMapAnnotations()
}
func loadMapAnnotations(){
for item in Globals.unsortedStoresList
{
Map.addAnnotation(item.Annotation)
do_table_refresh()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Globals.unsortedStoresList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomStoreCell = self.StoresListTable.dequeueReusableCellWithIdentifier("customStoreCell") as! CustomStoreCell
let s = Globals.unsortedStoresList[indexPath.row]
cell.loadItem(s.Name, StoreAddress: s.Address, StoreHoursOfOperation: s.HoursOfOperation, StoreDistanceFromCurrentLocation: String(s.DistanceFromCurrentLocation))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let s = Globals.unsortedStoresList[indexPath.row]
print(s.Name)
print(s.Address)
print(s.HoursOfOperation)
print(s.DistanceFromCurrentLocation)
//print("You selected cell #\(indexPath.row)!")
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.StoresListTable.reloadData()
return
})
}
AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate, StoresModelProtocoal {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let storesModel = StoresModel()
storesModel.delegate = self
storesModel.downloadItems()
return true
}
//////////////////////////////////////
//Delegates
//////////////////////////////////////
func itemsDownloaded(items: NSArray) {
print("Items downloaded")
for item in items
{
if let s = item as? Store
{
print(s.Address)
Globals.unsortedStoresList += [s]
//Map.addAnnotation(s.Annotation)
}
}
}
Any help would be appreciated, Thanks in advance.
I was able to find a temporarily solution to the problem
I modified StoreViewController.swift to this, if anyone is having a similar problem.
class StoreViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, StoresModelProtocoal {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawForm()
setUpMap()
self.hideKeyboardWhenTappedAround()
getCurrentLocation()
let hideStoreDetail: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideStoreDetails))
Map.addGestureRecognizer(hideStoreDetail)
//Create a nib for the custom cell and use it in the table
let nib = UINib(nibName: "CustomStoreCell", bundle: nil)
StoresListTable.registerNib(nib, forCellReuseIdentifier: "customStoreCell")
Globals.unsortedStoresList.removeAll() //I added this line of code to remove the old list
let storesModel = StoresModel()
storesModel.delegate = self
storesModel.downloadItems()
}
func itemsDownloaded(items: NSArray) {
print("Items downloaded")
for item in items
{
if let s = item as? Store
{
print(s.Address)
Globals.unsortedStoresList += [s]
Map.addAnnotation(s.Annotation)
}
}
do_table_refresh()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Globals.unsortedStoresList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomStoreCell = self.StoresListTable.dequeueReusableCellWithIdentifier("customStoreCell") as! CustomStoreCell
let s = Globals.unsortedStoresList[indexPath.row]
cell.loadItem(s.Name, StoreAddress: s.Address, StoreHoursOfOperation: s.HoursOfOperation, StoreDistanceFromCurrentLocation: String(s.DistanceFromCurrentLocation))
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let s = Globals.unsortedStoresList[indexPath.row]
print(s.Name)
print(s.Address)
print(s.HoursOfOperation)
print(s.DistanceFromCurrentLocation)
//print("You selected cell #\(indexPath.row)!")
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.StoresListTable.reloadData()
return
})
}

Segue on DidSelectRowAtIndexPath from Custom DataSource/Delegate Swift

My setup:
`UITableViewController` (ComboViewController)
-> Several Static Cells
-> One Static Cell contains a dynamic `tableView`
I need to use a custom Delegate/DataSource because the dynamic tableView is embedded in the Static TableView within the TableViewController
This custom Delegate/DataSource looks like this:
class DataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
// class variables
override init() {
super.init()
// initialize variables
}
//some data source/ delegate methods like number of rows, cellForRowAtIndexPath
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var indexedCombos: NSDictionary?
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let comboVC: ComboInfoViewController = storyboard.instantiateViewControllerWithIdentifier("ComboInfo") as! ComboInfoViewController
comboVC.doSegue()
}
}
Within ComboViewController I have this:
class ComboInfoViewController: UITableViewController {
func doSegue() {
self.performSegueWithIdentifier("tosingle", sender: combListTable)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "tosingle" {
//do stuff
}
}
}
If the segue is modal I get this error:
Warning: Attempt to present SingleProductViewController on ComboInfoViewController whose view is not in the window hierarchy!
If the segue is push, then the prepareForSegue method gets called, but the viewController does not push! What is happening?
I've searched and searched. But I have no idea what could be resulting in this behavior.
When you create the ComboInfoViewController instance with this line,
let comboVC: ComboInfoViewController = storyboard.instantiateViewControllerWithIdentifier("ComboInfo") as! ComboInfoViewController
You're creating a new instance that is not the one you have on screen, and never will be, so that's why you get the error. It is very important that you understand this concept; understanding how view controllers are created, and how to get pointers to ones that already exist is fundamental to iOS programming.
However, in this case you don't even need to get a pointer to the one on screen, because you should connect the segue directly from the cell (the dynamic prototype), which means you won't need any code to execute it. You can delete the didSelectRowAtIndexPath method, and the doSegue method. You only need to implement prepareForSegue. If you need to pass information to the next controller based one which row was touched, you can do it like below. The table view controller code should now look like this (this is an update of the code in my answer to this question, Swift: TableView within Static UITableViewCell),
class ComboInfoViewController: UITableViewController {
#IBOutlet weak var staticTableView: UITableView!
#IBOutlet weak var dynamicTableView: UITableView!
var dataSource = DataSource()
override func viewDidLoad() {
super.viewDidLoad()
dynamicTableView.dataSource = dataSource
dynamicTableView.delegate = dataSource
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row != 1 {
return 44
}else{
return 250 // the second cell has the dynamic table view in it
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "tosingle" {
var cell = sender as! UITableViewCell
var indexPath = dynamicTableView.indexPathForCell(cell)
var dataPoint = dataSource.theData[indexPath!.row] // theData is the array used to populate the dynamic table view in the DataSource class
// pass dataPoint to the next view controller which you get from segue.destinationviewController
println(dataPoint)
}
}
}

How do i refer to a variable that was made in another view controller in swift

How do i add the text to from my textfield into an array that is made in another ViewController.
class FirstViewController: UIViewController, UITableViewDelegate {
var thingsToDo = []
class SecondViewController: UIViewController {
#IBOutlet weak var enterTask: UITextField!
#IBAction func addtask(sender: AnyObject) {
thingsToDo += enterTask.text
}
You can use the prepareForSegue-method to pass objects to another viewcontroller. First you have to add global variable in your SecondViewController.
var theThingsToDo:[AnyObject]!
Then, in your FirstViewController, you can use the prepareForSegue-method and pass the value from your FirstViewController to your SecondViewController. It is important that you set the name of the segue in your Storyboard.
You can find the segue-identifier in the top right corner of Xcode:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.identifier == "yourSegueIdentifier" {
// Value of the FirstViewControllers variable 'thingsToDo' will be sent to the SecondViewController
(segue.destinationViewController as SecondViewController).theThingsToDo = thingsToDo
}
}
#IBAction func addtask(sender: AnyObject) {
theThingsToDo += enterTask.text
}

Using a Table View in a View Controller and wiring it up

I'm fairly new to xcode and Objective-C. Here is my problem:
I have a view controller with buttons and links to other view controllers on it.
On this view controller I have added a table view in which the cells will be used like a form
the cells will have text fields and labels
When trying to set this up and building it, it gives me an error saying I need to wire up my table view to the view controller somehow.
I know it is something to do with the data source and the table view delegate but I don't know how to wire the table view to the data source and delegate of my view controller.
Could anyone tell me how, or link me to an easy to follow guide on this?
Thanks
The easiest way would be to create a new Swift, or Objective-C Class and extend UITableViewController with it. This will create you a perfect sample code on how to write a UITableView DataSource and Delegate, which could be just copied.
After that, set your UITableViews delegate and datasource properties to self in viewdidload and implement UITableViewDataSource, UITableViewDelegate.
Edit
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var myTable: UITableView!
var myDataArray: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
myDataArray = NSArray(objects: "Peter", "Paul", "Marry")
myTable.dataSource = self
myTable.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: TableView DataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myDataArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
cell?.textLabel.text = myDataArray.objectAtIndex(indexPath.row) as NSString
return cell!
}
//MARK: TableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
I quickly wired you up some Swift Example code, where you can see how to connect a table view, with the DataSource and Delegate of your Class.