how to get the value of a label placed on table view cell - swift

I have a number of cells in my tableview each containing different label values
when i tap on the cell I want that value of label in next view controller. how do I get that?
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as!
MeetingsListTableViewCell
if self.meeting.count > 0{
let eachMeeting = self.meeting[indexPath.row]
cell.meetingTimeLabel?.text = (eachMeeting["time"] as? String) ?? "No Time"
cell.meetingDateLabel?.text = (eachMeeting["date"] as? String) ?? "No Date"
cell.idLabel?.text = (eachMeeting["id"] as? String) ?? "NO ID"
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main4", bundle:Bundle.main).instantiateViewController(withIdentifier: "MeetingDetailVC") as? MeetingDetailVC
self.navigationController?.pushViewController(vc!, animated: true)
}
i want that idLabel value to send in the next viewcontroller

Get the data always from the data source array meeting, never from the cell, for example
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let aMeeting = self.meeting[indexPath.row]
let identifier = aMeeting["id"] as! String
guard let vc = UIStoryboard.init(name: "Main4", bundle:Bundle.main).instantiateViewController(withIdentifier: "MeetingDetailVC") as? MeetingDetailVC else { return }
vc.identifier = identifier
self.navigationController?.pushViewController(vc, animated: true)
}
The code assumes that there is a property identifier in MeetingDetailVC
Notes:
For better readability you should name arrays in plural form (meetings).
The check self.meeting.count > 0 is pointless, cellForRowAt is not being called if the data source array is empty.
It's highly recommended to use a custom struct as data source rather than an array of dictionaries. You will get rid of all those annoying type casts.

Tapped cell can be accessed in didSelectRowAt function of tableVeiw. Extract tableView cell and cast int into your custom cell, after casting you can directly access value of lableId, add an optional property in MeetingDetailVC and pass value to it.

Related

Trying to bind an output to my tableviewCell UI Element in RxSwift

I have an output that lives in my VM and based on some change I want my textfield that resides in my custom tableviewCell to change in some way. I am unsure about how to have my UItextfield that lives in the tableviewcell bind to my output.
let index = IndexPath(row: 0, section: 0)
if let cell = tbl.cellForRow(at: index) as? TableViewCell {
print(cell.textF.text)
// Do whatever you want
}
I am not sure when you want to get the data, but if you want to do this when the user touches the cell, just implement the following method of UITableViewDelegate:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCellClass {
let cellLabelText = cell.yourTextField.text
// Do whatever you want with cellLabel
}
}

Thread 1: Fatal error: Index out of range from tableViewCell

I have error says "Thread 1: Fatal error: Index out of range".
on
cell.titleLabel.text = cellDataArrayPoster[indexPath.row].jobTitlePoster as? String
please notice that I'm using two different cells,
as prototypeCells. Moreover, they both have different identifier.
both arrays have getting their data from firebase.
var cellDataArray = [cellData]()
var cellDataArrayPoster = [cellDataPoster]()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellDataArray.count + cellDataArrayPoster.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = indexPath.row
if index == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! infoCell
cell.titleLabel.text = cellDataArray[indexPath.row].jobTitle as? String
cell.companyLabel.text = cellDataArray[indexPath.row].companyName
//cell.timeStampLabel.text = cellDataArray[indexPath.row].createdAt.calenderTimeSinceNow()
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellPoster", for: indexPath) as! infoCellPoster
cell.titleLabel.text = cellDataArrayPoster[indexPath.row].jobTitlePoster as? String
//cell.timeStampLabel.text = cellDataArray[indexPath.row].createdAt.calenderTimeSinceNow()
return cell
}
}
You misunderstood the concept of table view delegate methods. It is good to read more from the documentation.
My general rule of thumb is to always use only 1 array as data source for table view to avoid index out of range situations.
In your particular case the error is saying all about it - you are trying to reach index number that is out of range of the array. The easiest workaround will be to combine the two arrays in one, and have some sort of inheritance between the objects so they can fit.

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.

How to add a space between the subtitle and a comma between some of the words?

How would I add a space between the subtitle and a comma between some of the words? I'm using swift 3.
override
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
cell.detailTextLabel?.text = selectedItem.subThoroughfare! + selectedItem.thoroughfare!
+ selectedItem.locality! + selectedItem.administrativeArea! + selectedItem.postalCode!
return cell
}
The reason you are getting crash is because you are force wrapping the optional property of CLPlacemark, also if you want to join address try something like this. Make array of String? with all optional property that you are currently trying to make address without ! after that flatMap array to ignore the nil and then simply joined the array with separator ,.
override public tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
let addressArray = [selectedItem.subThoroughfare, selectedItem.thoroughfare, selectedItem.locality, selectedItem.administrativeArea, selectedItem.postalCode].flatMap({$0})
if addressArray.isEmpty {
cell.detailTextLabel?.text = "N/A" //Set any default value
}
else {
cell.detailTextLabel?.text = addressArray.joined(separator: ", ")
}
return cell
}
You are using forced unwrap on values and there is a possibility that one of the value is nil due to which you are getting the crash when code is trying to concatenate string to nil values.

click on TableViewCell to open profile view of current user

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)