click on TableViewCell to open profile view of current user - swift

I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell
let user = userList[indexPath.row]
cell.name.text = userList[indexPath.row].name
cell.location.text = userList[indexPath.row].location
if let imageURL = user.image {
cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
}
return cell
}
}

Using Code use didSelectRowAtIndexPath.
or
Using Storyboard:
step 1: select tableview cell.
step 2: Control + click mouse and drag in destination view.
step 3: Give Any of segue.
step 4: Done.

Add this below code
override func tableView(_ tableView: UITableView, didSelectRowAtindexPath: IndexPath){
let detailVC = storyboard.instantiateViewControllerWithIdentifier("MyDetailVC") as MyDetailVC // get the obect of other VC
detailVC.myImage = <your_image> // assign your image which you wanted to send to other VC.
self.navigationController?.pushViewController(detailVC,animated: true // Push to other VC
}
in MyDetailVC.swift
var myImage : UIImage? // Create variable of image type in required VC where you wanted to send data
Now use your Image in MyDetailVC.swift.
Any further query you can ask.

Just used UITableViewDelegate method "didSelectRowAtIndexPath" and send image to other view controller with its indexPath
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sb = UIStoryboard(name: "Main", bundle: nil)
let detailVC = sb.instantiateViewController(withIdentifier: "ImageVC") as! DetailViewController
detailVC.strImage = self.arrImage[indexPath.row]
self.navigationController?.pushViewController(detailVC, animated: true)
}
In DetailViewController take one variable
var strImage : String = ""
and assgin this variable to UIImagView
imgView.image = UIImage(named: strImage)

Related

My function tableView.didSelectRow is not working

I have a tableView with custom cells and my goal is to be able to click on one and print the number of the current row.
Right now when I click on a cell not happens and I can't understand why.
This is the code:
//MARK: - UITableDataSource
extension ChannelViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupResult.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let group = groupResult[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: K.cellContactNibName, for: indexPath) as! ContactCell
cell.usernameLabel.text = group.name
cell.messageLabel.text = group.recentMessage
let storage = Storage.storage()
let storageRef = storage.reference()
// Reference to an image file in Firebase Storage
let reference = storageRef.child("imagesFolder/\(group.image)")
// UIImageView in your ViewController
let imageView: UIImageView = cell.uImage
// Placeholder image
let placeholderImage = UIImage(named: "MeAvatar")
// Load the image using SDWebImage
imageView.sd_setImage(with: reference, placeholderImage: placeholderImage)
cell.uImage.image = imageView.image
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
}
}
and as you can see in the screen the single selection is enabled:
change to
extension ChannelViewController: UITableViewDataSource, UITableViewDelegate
or move the method into another extension conformed to UITableViewDelegate
also, remember to set the tableView's delegate to the ChannelViewController

unable to dequeue a cell with identifier cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

I am new to SWIFT and trying to show some data into table view controller but when I press the button it shows the above error. Please correct me
import UIKit
var selectedPlace : Place!
class ShowPlaceTableTableViewController: UITableViewController {
var places : [Place]!
override func viewDidLoad()
{
super.viewDidLoad()
places = readPlaces()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return places.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PlaceTableViewCell
cell.countryLabel.text = places[indexPath.row].country
cell.placeImageView.image = places[indexPath.row].picture
return cell
}
func readPlaces() -> [Place]
{
if UserDefaults.standard.object(forKey: "places") != nil
{
var data = UserDefaults.standard.object(forKey: "places") as! Data
let places = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! [Place]
return places
}else
{
return [Place]()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlace = places[indexPath.row]
performSegue(withIdentifier: "detailSegue", sender: self)
}
}
Is your PlaceTableViewCell inside it's own xib separately OR is it inside the storyboard itself? You must register either a cell class or a nib before you try to dequeue the cell from tableView.
If it's inside the storyboard, then you can register the subclass to work with it.
tableView.register(PlaceTableViewCell.self, forCellReuseIdentifier: "PlaceTableViewCell")
If it's inside it's own xib separately, then you can register the UINib to work with it.
tableView.register(UINib(nibName: "PlaceTableViewCell", bundle: nil), forCellReuseIdentifier: "PlaceTableViewCell")
These need to be called once only, you can place these calls inside viewDidLoad().
Now you can dequeue it like following -
let cell = tableView.dequeueReusableCell(withIdentifier: "PlaceTableViewCell") as! PlaceTableViewCell
Note : The reuseIdentifier must be same in following places -
storyboard (or xib)
at the time of registration tableView.register...
at the time of dequeue tableView.dequeue...

How to change the state of the image in cell made in xib?

There is a TableView and a "Locked" image, how do I get alpha = 0 when I click cell 1 in cell 2? There is the cellForRowAt function:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
cell.commonInit("got_\(indexPath.item)", title: titleLessons[indexPath.item], sub: summary[indexPath.item], imageLock: imageZ[indexPath.item])
return cell
}
There is the didSelectRowAt function:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if unlockedRows.contains(indexPath.row) {
let nextIndex = indexPath.row + 1
if nextIndex < pdfArr.count {
let vc = DetailLessonsVC()
let ce = TableViewCell()
vc.pdfTitle = pdfArr[indexPath.row]
vc.numberList = pdfArr[indexPath.row]
vc.linkList = link[indexPath.row]
unlockedRows.append(indexPath.row + 1)
self.navigationController?.pushViewController(vc, animated: true)
self.tableView.deselectRow(at: indexPath, animated: true)
}
print("no")
}
}
TableViewCell is xib's custom class.
You need to access the cell, and change image property, you can access the cell in didselect method with this:
let cell = tableView.cellForRowAtIndexPath(indexPath)
In your cell's custom class (TableViewCell) create an outlet for your image. If I understand correctly you want to edit cell located in the row number N+1 when user taps on the cell located in the row above, right?
If that's the case then all you have to do is get a reference to the next cell in didSelectRowAt. You can do just that this way:
var nextCellsIndexPath = indexPath
nextCellsIndexPath.row += 1
// Use 'if let' in order to make sure the cell at that index path exists
if let nexCell = tableView.cellForRow(at: nextCellsIndexPath) {
nextCell.lockedImage.alpha = 0
}
Since you didn't specify the number of sections in your table view, I assumed it has just one.

A sub view in UITableview gets disappear once the row is been clicked.

I'm working on a project in swift 3.0 where I have a UIView inside a UITableViewCell. For some reason once a row is been selected the view gets disappear, and once a a new row is been selected the view of the previous cell shows up and the view of the newly selected one gets disappear.Name of the view that gets disappear is redView(reference of the code bellow). My code and UITableView delegates as follow.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.clear
cell.selectedBackgroundView = backgroundView
let data = self.mediaList[indexPath.row] as! NSDictionary
let redView = cell.viewWithTag(TABLE_CELL_TAGS.redView)!
let reducedPriceLabel = cell.viewWithTag(TABLE_CELL_TAGS.reducedpricelable) as! UILabel
Utils.setTableCellLabelText(cell: cell, labelTag: TABLE_CELL_TAGS.title, text: data["title"] ?? "title...")
if let reducedPrice = data["mediaValue"] as? Int{
reducedPriceText = "$\(String(reducedPrice))"
redView.isHidden = false
reducedPriceLabel.isHidden = false
}else{
redView.isHidden = true
reducedPriceLabel.isHidden = true
}
Utils.setTableCellLabelText(cell: cell, labelTag: TABLE_CELL_TAGS.reducedpricelable, text: reducedPriceText)
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let mP3ViewController = self.storyboard?.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
mP3ViewController.mediaDetails = mediaList[indexPath.row] as? NSDictionary
self.navigationController?.pushViewController(mP3ViewController, animated:true)
}
Go to the storyboard setting of tableViewcell set selection to None. then I think it will work for you.
Try this and let me know.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let mP3ViewController = self.storyboard?.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
mP3ViewController.mediaDetails = mediaList[indexPath.row] as? NSDictionary
self.navigationController?.pushViewController(mP3ViewController, animated:true)
}

UIViewController when UITableViewCell is Pressed

I am trying to make an app so that when the cell in the UITableView is pressed, it opens a new ViewController with the same image and label used before in the initial cell that was clicked.
Here are my cells:
Here is the array I am using:
let alligator:NSArray = ["American Alligator","American Crocodile","Mugger Crocodile","Saltwater Crocodile"]
Here is the numberOfRowsInSection and cellForRowAt:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(alligator.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell4 = tableView.dequeueReusableCell(withIdentifier: "cell4", for: indexPath) as! AlligatorViewCell
cell4.alligatorImage.image = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")
cell4.alligatorLabel.text = alligator[indexPath.row] as? String
return(cell4)
}
Here are my outlets for the detail View Controller:
#IBOutlet var detailImage: UIImageView!
#IBOutlet var detailLabel: UILabel!
And here is the didSelectRowAt
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
detailImage.image = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")!
detailLabel.text = alligator[indexPath.row] as? String
The problem is that when I press the cell, I get the error, fatal error: Unexpectedly found nil while Unwrapping Optional
I believe your error is occurring because detailImage does not exist when you call it.
From what I understand, these outlets are in your base view controller, but they are referring to objects in your detail view controller, which isn't allowed. Thus when you try and call them, they won't pass anything giving a value of nil.
Thus it is not about the UIImage being initialized.
You need to make the IBOutlets within the detailViewController class, and then pass the values from your cell to these outlets through your prepareForSegue func.
Let me know if you have questions about this.
Edit
Let's say your detail view controller has the detailImage property, then you could do something like this (in your base ViewController)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination as! UIViewController //your detail controller
controller.detailImage = myImage //where myImage is a property of your base view controller
}
Edit
You could set the myImage property in the view controller when your cell is tapped just as your tried before. Then myImage could be set to the detailImage in the prepareForSegue func. So something like this:
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myImage = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")!
...
Edit
You should be using myImage like this:
var myImage: UIImage?
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myImage = UIImage.init(named: alligator[indexPath.row] as! String + ".jpg")!
...