working with cell on tableview using swift 2 - ios

I am developing a app using Swift 2. In my app I am parsing JSON data to a table view. When I tap a cell it successfully moves to another view controller but I am unable to fetch the json data.
This is the code in my view controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath){
var cell = self.TableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! CustomTableCell
let strbookdetail : NSString=arrDict[indexPath.row] .valueForKey("booking_detail") as! NSString
let strdrop : NSString=arrDict[indexPath.row] .valueForKey("drop_address") as! NSString
cell.Bookdetail.text=strbookdetail as String
cell.Dropaddress.text=strdrop as String
return cell as CustomTableCell
}
//It helps to parse JSON data to table view.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
TableView.deselectRowAtIndexPath(indexPath, animated: true)
let tripcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("UpcomingController") as! Secondcontroller
navigationController?.pushViewController(tripcontroller, animated: true)
}
When tapping on the cell it helps to move to other view controller SecondController
In my SecondController I have two UILabels. In those labels I want to show data i.e strbookdetail and strdrop
How can I pass a reference between the two view controllers?

It is easy to do using property pass data:
In 2th vc:
var dataFromBeforeVC:[String:String] = [String:String]()
override func viewDidLoad() {
super.viewDidLoad()
initData ()
}
func initData() {
// set data strbookdetail and strdrop to labelOne & labelTwo
labelOne.text = dataFromBeforeVC["strdrop"]
labelTwo.text = dataFromBeforeVC["strbookdetail"]
}
In 1th vc:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
TableView.deselectRowAtIndexPath(indexPath, animated: true)
let tripcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("UpcomingController") as! Secondcontroller
let cell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
let strbookdetail : NSString=arrDict[indexPath.row] .valueForKey("booking_detail") as! NSString
let strdrop : NSString=arrDict[indexPath.row] .valueForKey("drop_address") as! NSString
tripcontroller.dataFromBeforeVC = [
"strdrop":strbookdetail,
"strdrop":strbookdetail
]
self.navigationController?.pushViewController(tripcontroller, animated: true)
}

Related

When select cell to pass data always shows nil in the next ViewController using Swift

I am trying to pass data when select or press cell in TableView, it's working and I can print the result while select that cell.
The problem when the second view shows the data is nil.
her is the code when when select cell:
var feedItems: NSArray = NSArray()
var selectedPlayer : UsersModel = UsersModel()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: WinnerTableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! WinnerTableCell
// Get the location to be shown
let item: UsersModel = feedItems[indexPath.row] as! UsersModel
// Get references to labels of cell
myCell.lbTextName!.text = item.name
myCell.lbScore!.text = item.score
let imageURL = URL(string: "https://mywebsite.com/image-upload/img/\(item.userImage ?? "nil")")
myCell.userImage.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "nullImageQuestion.png"))
return myCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = feedItems[indexPath.row] as! UsersModel
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.name = selectedPlayer.name ?? "nil"
print("Print When select cell \(selectedPlayer.name ?? "nil")")
}
And her is the code in the second view:
#IBOutlet weak var lbName: UILabel!
#IBOutlet weak var userImage: UIImageView!
var name = ""
var selectedUser : UsersModel?
override func viewDidLoad() {
super.viewDidLoad()
lbName.text = selectedUser?.name
print("Print when second view open via viewdidload \(selectedUser?.name ?? "nil")")
// Do any additional setup after loading the view.
}
I tried to print from the second view but it shows nothing. What mistake I did?
This is what i have out when print:
There is something I can not understand when I print, it start with the secondview?
Note: I am not using Navigation Controller.
Thanks
There are two serious issues:
The main issue is that you assign the name to the name property but you are assigning selectedUser?.name to the label in the destination controller which is of course nil
The second issue has already been fixed by Taimoor: You have to present or push the controller.
So replace didSelect with
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = feedItems[indexPath.row] as! UsersModel
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.selectedUser = selectedPlayer
self.present(nextViewController, animated: true)
}
And please never use NSArray in Swift. Declare the data source array
var feedItems = [UsersModel]() // why not just `User`?
and delete all unnecessary type casts.
You have to use pushViewController to take the data to next screen. Just add one more line in didSelectRowAt function as below:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = feedItems[indexPath.row] as! UsersModel
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.name = selectedPlayer.name ?? "nil"
print("Selcted \(selectedPlayer.name ?? "nil")")
self.navigationController?.pushViewController(nextViewController, animated: true)
}
This will take your data to next screen.
You can also try to execute "nextViewController.loadViewIfNeeded()"
Because you just created this ViewController, but did not present it, according to your hierarchical relationship, choose to use prensent or push to present it, it will execute "ViewDidload()"
you've given feedItems's array type NSArray() instead to
var feedItems: UsersModel = [ ]
or you assign name to selectedUser?.name of next page so that assign nil value
or that probably wrong
you have to implement at didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.name = feedItems[indexPath.row].name as! UsersModel
print("Selcted \(selectedPlayer.name ?? "nil")")
self.navigationController?.pushViewController(nextViewController, animated: true)
}

Passing selected Image in cell image

My application consists of 2 tap bars.
First tap is TableView and second - VC.
When I'm on first VC, I selected picture and press the button, which should transfer the selected picture on cell image.
I'm trying to save image in UserDefaults but then it turns out that all lines are with the same picture
In my VC, I save TextField by this method:
func saveButton() {
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items:[String]
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(nameTextField.text!)
} else {
items = [nameTextField.text!]
}
UserDefaults.standard.set(items, forKey: "items")
nameTextField.text = ""
navigationController?.popViewController(animated: true)
}
And choose the image
Then I tap "Save" button
In my Table view:
override func viewDidAppear(_ animated: Bool) {
// Load Item Func
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
}
table.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellPrototype
// Configure the cell...
cell.pointNameLabel.text = items[indexPath.row]
return cell
}
You can pass image by creating a variable in Second VC like this
UITableView Delegate Method
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as? YourCell
if let DetailVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController{
DetailVC.Selected_image = cell.YourImageView.image
self.navigationController?.pushViewController(DetailVC,animated: true)
}
}
Create Variable in Second VC
class DetailViewController: UIViewController {
var Selected_image: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
print(Selected_image)
}
}
You can pass the image from cell to detailViewController here is partail pseudo Code
tableView (cell , didSelectCellAtIndexPath) {
if let cell = cell as? CustomCell {
let image = cell.image
let detailVC = DetailViewController(..) // instantiate from storyboard
detailVC.selectedImage = image
navigationViewController.push(detailVC)
}
}
Class DetailVC: UIViewController {
var selectedImage: UIImage!
// can access image anywhere in this class after passing
}

iOS How to send cell data to another VC use parse Swift

How i can send data from my table view cell, to another VC when in tap on cell.
My code for fetch data from DB:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! cellRequestsTVC
let good = data[indexPath.row]
name = good["username"] as! String
cell.userNameLable.text = "#\(name)"
area = good["place"] as! String
cell.areaLable.text = "\(area)"
cell.descriptionLable.text = good["description"] as? String
cell.priorityLable.text = "Priority " + ((good["priority"] as? Int)?.description)!
let imageProblems = good["image"] as? PFFile
imageProblems?.getDataInBackground{ (imageData, error)in
if imageData != nil {
let image = UIImage(data: imageData!)
cell.problemImage.image = image
}
}
return cell
}
It's working perfect. But now my target open data from cell in another VC.
Example:
Example
You have to implement UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let good = data[indexPath.row]
// Here you can either perform a segue or push view controller to UINavigationController
//Push View controller
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : DetailViewController = storyBoard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.sharedData = data // here you pass data
self.navigationController?.pushViewController(vc, animated: true)
}
In DetailViewController create object of data with required type
var sharedData : [String : Any]! // Take optional variable if object can be nil & here assuming data contains object of type [String : Any]
You can look the documentation here
UITableViewDelegate

How to pass only one key value pair from array?

The following is my json response....
{"Doctor":[{"doctorname":"ANBU SURESH RAO, D.ORTHO., MSORTHO.,","presid":"1008"}]}
The following is my viewcontroller code.......
let parameters: Parameters=["hnum":hnum!]
Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
{
response in
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject>{
if let innerDict = dict["Doctor"]{
self.namesarray = innerDict as! [AnyObject]
self.jsontable.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesarray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CustomTableViewCell
let name = namesarray[indexPath.row]["doctorname"]
cell?.lbldocname.text = name as? String
flag = !flag
flagcheck()
return cell!
}
This view controller loads only my doctor name, so when i click the doctor name I want the presid only to be passed on to the next view controller.... I tried with prepareForSegue it didnt work....any ideas????
tableView:didSelectRowAtIndexPath:
Tells the delegate that the specified row is now selected. Use indexPath to locate the new selected row in tableView.
Check my previous SO ans for details.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let pressId = namesarray[indexPath.row]["presid"]
if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController ") as? SecondViewController {
viewController.pressId= pressId
if let navigator = navigationController {
navigator.pushViewController(viewController, animated: true)
}
}
}
Declare a global variable pressId in SecondViewController so that you can access it from your current controller class.
Declare a global variable selectedPresId. Implement didSelectRowAtIndexPath method and in that method set the pres id in that global variable
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedPresId = namesarray[indexPath.row]["presid"]
self.performSegue(withIdentifier: "detailSegue", sender: self)
}
In prepareForSegue do this
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSegue" {
let vc = segue.destination as! ViewController
vc.selectedPresId = selectedPresId
}
And in your second view controller create a property with the name - selectedPresId so that you can set it in above line vc.selectedPresId

How to share data of tableViewCell to next viewController without using storyboard in ios with Swift

I am using Xib files in my project for building interface of my app.
I have a tableView in my first viewController from which I want to pass data to next ViewController. I have created a custom cell for my tableView which contains an imageView and two labels.
This is my code
import UIKit
class YASProductListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// registering my custom cell
tableView.registerNib(UINib(nibName: "YASProductListTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell")
let cell : YASProductListTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! YASProductListTableViewCell
cell.productNameLabel.text = prodcutNames[indexPath.row]
cell.productDetailLabel.text = productDetail[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return prodcutNames.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 140
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! YASProductListTableViewCell
let destination = YASProductDetaiilViewController(nibName: "YASProductDetaiilViewController", bundle: NSBundle.mainBundle())
destination.productImage = cell.productImageView.image
destination.productTitle = cell.productNameLabel.text!
let productDetails = YASProductDetaiilViewController(nibName: "YASProductDetaiilViewController", bundle: nil) as YASProductDetaiilViewController
navigationController?.navigationBarHidden = false
navigationController?.title = ""
navigationController?.pushViewController(productDetails, animated: true)
}
Now what I want to do is pass the image and labels text to next viewController when user tap on any cell. Here is the code of next ViewController
import UIKit
class YASProductDetaiilViewController: UIViewController {
#IBOutlet weak var productImageView: UIImageView!
#IBOutlet weak var productTitleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupViewControllerUI()
// Do any additional setup after loading the view.
}
// MARK: - UIViewController helper Methods
func setupViewControllerUI(){
productImageView.image = productImage
productTitleLabel.text = productTitle
}
}
As you can see I have tried it didSelectRowAtIndexPath but its not working. Please help! Thanks
You are using right method to share data between viewController. However you have made a mistake. You are creating two instance of your ProductDetailViewController. You need to create only one instance of destination ViewCotroller and then set its properties accordingly you you can simply replace your didSelectRowAtIndexPath method with following
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! YASProductListTableViewCell
let productDetails = YASProductDetaiilViewController(nibName: "YASProductDetaiilViewController", bundle: nil) as YASProductDetaiilViewController
productDetails.productImage = cell.productImageView.image
productDetails.productTitle = cell.productNameLabel.text!
navigationController?.pushViewController(productDetails, animated: true)
}
I hope it will work.
Change your didSelect method like below code,
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! YASProductListTableViewCell
let productDetails = YASProductDetaiilViewController(nibName: "YASProductDetaiilViewController", bundle: nil) as YASProductDetaiilViewController
navigationController?.navigationBarHidden = false
navigationController?.title = ""
productDetails.productImage = cell.productImageView.image
productDetails.productTitle = cell.productNameLabel.text!
navigationController?.pushViewController(productDetails, animated: true)
}
Hope this helps you.
Do as follow might be help you.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! YASProductListTableViewCell
let objYASProductDetaiilViewController = self.storyboard?.instantiateViewControllerWithIdentifier("STRORYBOARD_ID") as? YASProductDetaiilViewController
objYASProductDetaiilViewController.productImage = cell.productImageView.image
objYASProductDetaiilViewController.productTitle = cell.productNameLabel.text!
self.navigationController?.pushViewController(objMedicalDevicesVC!, animated: true)
navigationController?.navigationBarHidden = false
navigationController?.title = ""
navigationController?.pushViewController(objYASProductDetaiilViewController, animated: true)
}
Here You can not assign a image View to image View directly.You need to get a image first then it give to a other view controller image then set it to image to UIImage
import UIKit
class YASProductDetaiilViewController: UIViewController {
#IBOutlet weak var productImageView: UIImage!
#IBOutlet weak var productTitleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupViewControllerUI()
// Do any additional setup after loading the view.
}
// MARK: - UIViewController helper Methods
func setupViewControllerUI(){
productImageView.image = productImage
productTitleLabel.text = productTitle
}
}
create dictionary of all the needed information and the add to array and get using indexpath.row when cell is clicked
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var dicTemp=prodcutNames[indexPath.row] as! NSMutableDictionary
let destination = YASProductDetaiilViewController(nibName: "YASProductDetaiilViewController", bundle: NSBundle.mainBundle())
destination.productImage = prodcutNames.valueForKey("imageObj") //get image object
destination.productTitle = prodcutNames.valueForKey("product_title")//get product title
let productDetails = YASProductDetaiilViewController(nibName: "YASProductDetaiilViewController", bundle: nil) as YASProductDetaiilViewController
navigationController?.navigationBarHidden = false
navigationController?.title = ""
navigationController?.pushViewController(productDetails, animated: true)
}

Resources