Passing data to Segment control from Table view Cell - ios

I am using table view cell to display the data . I have a segment control . In first section I am displaying the list of the move with button control . When the user click the check mark button I want to send those table view cell values to seconds control and added to on it .. Please give me some sample code based on the below code ..
Here is the table view cell .
import UIKit
protocol CellSubclassDelegate: AnyObject {
func buttonTapped(cell: MovieViewCell)
}
class MovieViewCell: UITableViewCell {
weak var delegate:CellSubclassDelegate?
static let identifier = "MovieViewCell"
#IBOutlet weak var movieImage: UIImageView!
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var movieOverview: UILabel!
#IBOutlet weak var someButton: UIButton!
#IBAction func someButtonTapped(_ sender: UIButton) {
self.delegate?.buttonTapped(cell: self)
}
func configureCell(title: String?, overview: String?, data: Data?) {
movieTitle.text = title
movieOverview.text = overview
movieImage.image = nil
if let imageData = data{
movieImage.image = UIImage(data: imageData)
// movieImage.image = nil
}
}
}
Table View Cell for row code ..
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell
let row = indexPath.row
let title = presenter.getTitle(by: row)
let overview = presenter.getOverview(by: row)
let baseImageURL = presenter.getUrlImage(by: row)
let data = presenter.getImageData(by: baseImageURL)
cell.delegate = self
cell.configureCell(title: title, overview: overview, data: data)
return cell
}
Here is the code implementation of delegate .
extension MovieViewController : CellSubclassDelegate{
func buttonTapped(cell: MovieViewCell) {
guard (self.tableView.indexPath(for: cell) != nil) else {return}
let customViewController = storyboard?.instantiateViewController(withIdentifier: "MovieDeatilsViewController") as? MovieDeatilsViewController
customViewController?.titlemovie = cell.movieTitle.text ?? ""
customViewController?.imagemovie = cell.movieImage.image
customViewController?.overview = cell.movieOverview.text ?? ""
// customViewController?.movieTitleHeader.text = cell.movieTitle.text ?? ""
self.navigationController?.pushViewController(customViewController!, animated: true)
}
}
Did select methods implementation ..
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dc = storyboard?.instantiateViewController(withIdentifier: "MovieDeatilsViewController") as! MovieDeatilsViewController
let row = indexPath.row
dc.titlemovie = presenter.getTitle(by: row) ?? ""
dc.overview = presenter.getOverview(by: row) ?? ""
let baseImageURL = presenter.getUrlImage(by: row)
dc.imagemovie = UIImage(data: presenter.getImageData(by: baseImageURL)!)
self.navigationController?.pushViewController(dc, animated: true)
}
}
Here is the screenshot of the applications .
When the user click check box I want to add those table view cell values into favourite segment control

Am example of what you need to achieve (The name of method and variables are not the exact ones, it just to help you understand the principle). In this case with only one table view:
struct MoviePresenter {
var nbRows: Int = 0
}
class MoviesVC {
var presenter = MoviePresenter()
var tableViewSelect : UISegmentedControl!
var movieTableView: UITableView!
var favoriteMovies = [Int]() // the list of row of favorite movies
// utility function to know if movie is favorite or not
func isInFavorites(_ row: Int) -> Bool {
return favoriteMovies.first(where: {$0 == row}) != nil
}
// Note : all table view datasource/delegate methods need to check
// which is the current selected display
func numberOfRowsInSection(_ section: Int) -> Int {
if tableViewSelect.selectedSegmentIndex == 0 {
return presenter.nbRows
} else {
return favoriteMovies.count
}
}
// in cellForRow
func cellForRow(indexPath: IndexPath) {
if tableViewSelect.selectedSegmentIndex == 0 {
// default display
let cell = UITableViewCell() // you dequeue your cell here
// init cell for presenter (by: row)
if isInFavorites(indexPath.row) {
// checkMark handling
}
// to handle checkmark
cell.tag = indexPath.row
} else {
// favorite list
let cell = UITableViewCell() // you dequeue your favorite cell here
let row = favoriteMovies[indexPath.row]
// if you want to handle checkmark
cell.tag = row
}
}
func checkMarkTappedInFavoriteCell(cell: UITableViewCell) {
let row = cell.tag
// set/unset favorite check mark when tapped
if isInFavorites(row) {
favoriteMovies.removeAll(where: {$0 == row})
} else {
favoriteMovies.append(row)
}
movieTableView.reloadRows(at: [IndexPath(row: row, section: 0)], with: .none)
}
// action to be executed when selected segment changes
#IBAction func tableViewSelectedIndexChanged(_ sender: UISegmentedControl) {
self.movieTableView.reloadData()
}
}
This only in the case you want only one table view. In case you want 2 table views the change in segmented control will also make one tableview visible and the other invisible.

Related

Subtitles wont display on table views in Swift 5 despite being a subtitled table view cell

I'm working on a project that needs to display two table views at once that each draw from their own class, but no matter what I try, I can't get subtitles to display. The table view cells are formatted to subtitle, and it recognizes detailed text labels, but it just displays only the main text, or just an empty cell.
-------main story board-------
import UIKit
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableViewOne: UITableView!
#IBOutlet weak var eraserSwitch: UISwitch!
#IBOutlet weak var tableViewTwo: UITableView!
var topShelf: [Top] = []
var bottomShelf: [Bottom] = []
//var topShelf = ["Milk", "Eggs", "Yogurt"]
//var bottomShelf = ["Lettuce", "Carrots", "Onions"]
override func viewDidLoad() {
super.viewDidLoad()
topShelf.append(T1)
topShelf.append(T2)
bottomShelf.append(B1)
bottomShelf.append(B2)
// Do any additional setup after loading the view.
tableViewOne.register(UITableViewCell.self, forCellReuseIdentifier: "cellIDOne")
tableViewOne.delegate = self
tableViewOne.dataSource = self
tableViewTwo.register(UITableViewCell.self, forCellReuseIdentifier: "cellIDTwo")
tableViewTwo.delegate = self
tableViewTwo.dataSource = self
}
#IBAction func switchPressed(_ sender: UISwitch) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == tableViewOne {
return topShelf.count
}
return bottomShelf.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == tableViewOne {
let cell = tableViewOne.dequeueReusableCell(withIdentifier: "cellIDOne", for: indexPath)
// cell.textLabel?.text = topShelf[indexPath.row].description
cell.textLabel?.text = topShelf[indexPath.row].item
//cell.textLabel?.text = "a"
// cell.detailTextLabel?.text = topShelf[indexPath.row].experationDate
//cell.detailTextLabel?.text = "a"
cell.detailTextLabel?.text = "v"
//print(topShelf[indexPath.row].experationDate)
return cell
} else {
let cell = tableViewTwo.dequeueReusableCell(withIdentifier: "cellIDTwo", for: indexPath)
// cell.textLabel?.text = bottomShelf[indexPath.row]
cell.textLabel?.text = bottomShelf[indexPath.row].item
cell.detailTextLabel?.text = bottomShelf[indexPath.row].experationDate
//print(bottomShelf[indexPath.row].experationDate)
//USE THIS CODE AS A SKELETON FOR ADDING, ERASING, AND MARKING
// if playlist[indexPath.row].Favorite == true {
// cell.detailTextLabel?.text = "\(playlist[indexPath.row].artistName) ♥"
// } else {
// cell.detailTextLabel?.text = "\(playlist[indexPath.row].artistName) \(playlist[indexPath.row].playCount)"
// }
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableViewOne {
// first table clicked, use for eraser
tableViewOne.deselectRow(at: indexPath, animated: true)
print("clickOne")
} else {
// you clicked the second table
tableViewTwo.deselectRow(at: indexPath, animated: true)
print("clickTwo")
}
}
-------Class-------
import Foundation
class Top {
var item: String
var retrievalDate: String
var experationDate: String
init(item: String, retrievalDate: String, experationDate: String) {
self.item = item
self.retrievalDate = retrievalDate
self.experationDate = experationDate
}
}
class Bottom {
var item: String
var retrievalDate: String
var experationDate: String
init(item: String, retrievalDate: String, experationDate: String) {
self.item = item
self.retrievalDate = retrievalDate
self.experationDate = experationDate
}
}
let T1 = Top(item: "Milk", retrievalDate: "10/11/22", experationDate: "10/22/22")
let T2 = Top(item: "Yogurt", retrievalDate: "10/11/22", experationDate: "10/20/22")
let B1 = Bottom(item: "Carrots", retrievalDate: "10/11/22", experationDate: "11/1/22")
let B2 = Bottom(item: "Lettuce", retrievalDate: "10/11/22", experationDate: "12/3/22")

Sending a signal to collection view within tableview cell from a segment outlet in another tableview cell

I have a segment outlet in a tableview cell in a VC. There are two indexes: 1 and 2.
When I click on 2, I want to tell the collection view within another tableviewcell to reload another view.
And when I click back to 1, I want the same collection view to reload again and display the original content.
Here are my View Controller Functions:
class MyProfileTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,segment
{
//Variable selection to determine what is selected - 1 by default
var viewSelected = "1"
//Segment Function - viewSelected is used to tell VC what index it's on
func segmentSelected(tag: Int, type: String) {
if type == "1" {
print("1")
viewSelected = "1"
} else if type == "2" {
print("2")
viewSelected = "2"
}
}
//Cell For Row - tells tableviewcell to look at viewSelected
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = AboutTableView.dequeueReusableCell(withIdentifier: "ProfileSegmentTableViewCell", for: indexPath) as! ProfileSegmentTableViewCell
cell.segmentCell = self
return cell
} else {
let cell = AboutTableView.dequeueReusableCell(withIdentifier: "1_2Cell", for: indexPath) as! 1_2Cell
cell.viewSelected = viewSelected
return cell
}
Here is the Segment Control TableviewCell
//protocol used to delegate
protocol segment: UIViewController {
func segmentSelected(tag: Int, type: String)
}
class ProfileSegmentTableViewCell: UITableViewCell {
#IBOutlet weak var profileSegmentControl: UISegmentedControl!
var segmentCell: segment?
#IBAction func segmentPressed(_ sender: Any) {
profileSegmentControl.changeUnderlinePosition()
let Index = self.profileSegmentControl.selectedSegmentIndex
if Index == 0
{
segmentCell?.segmentSelected(tag: (sender as AnyObject).tag, type: "1")
)
} else {
segmentCell?.segmentSelected(tag: (sender as AnyObject).tag, type: "2")
}
}
CollectionView
//variable by default
var viewSelected = "1"
//viewDidLoad
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
cView.delegate = self
cView.dataSource = self
get {
self.cView.reloadData()
self.cView.layoutIfNeeded()
}
}
func get(_ completionHandler: #escaping () -> Void) {
getCount.removeAll()
if viewSelected = "1" {
print("1") } else {
print("2)
}
completionHandler()
}
Here's a very simple example of using a closure so your segmented-control cell can communicate with your table view controller.
Your cell class might look like this:
class ProfileSegmentTableViewCell: UITableViewCell {
#IBOutlet var profileSegmentControl: UISegmentedControl!
var callback: ((Int)->())?
#IBAction func segmentPressed(_ sender: Any) {
guard let segControl = sender as? UISegmentedControl else { return }
// tell the controller that the selected segment changed
callback?(segControl.selectedSegmentIndex)
}
}
When the user changes the selected segment, the cell uses the callback closure to inform the controller that a segment was selected.
Then, in your controller, you could have a var to track the currently selected segment index:
// track selected segment index
var currentIndex: Int = 0
and your cellForRowAt code would look like this:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
// first row - use cell with segemented control
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileSegmentTableViewCell", for: indexPath) as! ProfileSegmentTableViewCell
// set the segemented control's selected index
cell.profileSegmentControl.selectedSegmentIndex = self.currentIndex
// set the callback closure
cell.callback = { [weak self] idx in
guard let self = self else {
return
}
// update the segment index tracker
self.currentIndex = idx
// reload row containing collection view
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
return cell
} else if indexPath.row == 1 {
// second row - use cell with collection view
let cell = tableView.dequeueReusableCell(withIdentifier: "1_2Cell", for: indexPath) as! My_1_2Cell
// tell the cell which segment index is selected
cell.setData(currentIndex)
return cell
}
// all other rows - use simple Basic cell
let cell = tableView.dequeueReusableCell(withIdentifier: "PlainCell", for: indexPath) as! PlainCell
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
Here is a complete example you can run and examine: https://github.com/DonMag/ClosureExample
You can use NotificationCenter.default.addObserver... method and NotificationCenter.default.post..... Read about them. And don't forget to remove observers in deinit

How Can I show data to tableView From Array which belong in model array object in UITableView?

i have a model object it have a array i m populating data by indexPath.row than i need to send every section array to another tableView but it sending me random data how can i send specific selected rows array to next tableView ? please help me to make understand ..
here is My Model Object :
class ProductModel {
var name:String
var option: [String]
var image:UIImage
init(name:String,option:[String],image:UIImage) {
self.image = image
self.name = name
self.option = option
}
}
Here is my Model Object :
class Data {
static var product = [ProductModel]()
}
Here is Data function For Append Data
static func read(compleationHandler:#escaping () -> ()) {
let hospitalList:[String] = ["A","B,C"]
let hospitalTwo:[String] = ["Sharee bangla","National Park","bangladesh medical"]
let hospitalThree:[String] = ["NSU","MIU","UIU","AIUB"]
let hospitalFour:[String] = ["Dhaka","Comillah","Borials"]
let hospitalFive:[String] = ["iPhone","iPad","iMac"]
DispatchQueue.global(qos: .userInteractive).async {
if Data.product.count == 0 {
Data.product.append(ProductModel(name: "Mahmud", option: hospitalList, image: #imageLiteral(resourceName: "radio")))
Data.product.append(ProductModel(name: "Rangon", option: hospitalTwo, image: #imageLiteral(resourceName: "pause.on.fw")))
Data.product.append(ProductModel(name: "Saikot", option: hospitalThree, image: #imageLiteral(resourceName: "Unit.fw")))
Data.product.append(ProductModel(name: "Ratul", option: hospitalFour, image: #imageLiteral(resourceName: "Region.fw")))
Data.product.append(ProductModel(name: "Jubayer", option: hospitalFive, image: #imageLiteral(resourceName: "add-note.fw")))
}
DispatchQueue.main.async {
compleationHandler()
}
}
}
Here is first ViewDidLoad and a global array for store cell arary :
class ModelTableView: UIViewController {
var optionData:[String] = [String]()
#IBOutlet var ModelDataTableVIew: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
ModelDataTableVIew.delegate = self
ModelDataTableVIew.dataSource = self
ModelFunction.read { [weak self] in
self?.ModelDataTableVIew.reloadData()
}
}
}
Here is cellForRowAtIndex here i created in my label i add a tap Gesture .when user click it show another tableView with this cell array data
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == Data.product.count {
let cell = ModelDataTableVIew.dequeueReusableCell(withIdentifier: "modelCellBtn") as! ModelCellBtn
return cell
} else {
let cell = ModelDataTableVIew.dequeueReusableCell(withIdentifier: "modelCell") as! ModelCell
cell.configureCell()
optionData = Data.product[indexPath.section].option
let tapGeshture = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
cell.optionLabel.addGestureRecognizer(tapGeshture)
cell.nameImage.image = Data.product[indexPath.row].image
return cell
}
Here is prepare Segue and sending Data to next view controller :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "option") {
let dest = segue.destination as! OptionViewController
dest.data = optionData
}
}
Here is my nextViewController (For show option Data):
class OptionViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var data:[String] = []
#IBOutlet weak var optionTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
optionTableView.delegate = self
optionTableView.dataSource = self
print(data)
optionTableView.reloadData()
ModelFunction.read { [weak self] in
self?.optionTableView.reloadData()
}
}
}
Here option View Controller and in this controller i want to show retrieved array show in tableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = optionTableView.dequeueReusableCell(withIdentifier: "optionCell") as! OptionCell
//cell.textLabel?.text = Data.product[indexPath.section].option[indexPath.row]
cell.textLabel?.text = data[indexPath.row]
return cell
}
But its showing me single section data in my tableView ..
You are taking the optionData in your cellForRow method, which is always taking the lastVisible data, You should take the optionData in your didSelectRowAt method
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("didselect")
optionData = Data.product[indexPath.row].option
performSegue(withIdentifier: "option", sender: self)
}
Try and share your results.

how can I reset all switches in tableview from CustomCell

I've set a Switch as part of a tableView cell and set up a CustomCell class to deal with the action, the class looks like this
class SwitchTableViewCell: UITableViewCell {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var `switch`: UISwitch!
var switchAction: ((Bool) -> Void)?
#IBAction func switchSwitched(_ sender: UISwitch) {
switchAction?(sender.isOn)
}
}
What I need to do now is to ensure that when one Switch is turned on, all the other Switches in the other rows are turned off. The table rows are loaded like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let thisRow = rowData[indexPath.row]
switch thisRow.type {
case .text:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "textfieldCell", for: indexPath) as? MovingTextFieldTableViewCell else {
Logger.shared.log(.app, .error, "Could not load TextFieldTableViewCell")
fatalError()
}
cell.textField.textFieldText = thisRow.data as? String
cell.textField.labelText = thisRow.title
cell.dataChanged = { text in
thisRow.saveData(text)
}
cell.errorLabel.text = nil
return cell
case .switch:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as? SwitchTableViewCell else {
Logger.shared.log(.app, .error, "Could not load SwitchTableViewCell")
fatalError()
}
cell.label.text = thisRow.title
cell.switch.isOn = thisRow.data as? Bool ?? false
cell.switchAction = { isOn in
thisRow.saveData(isOn)
}
return cell
}
}
There are two types for thisRow in each row (Text/Switch) and the saveData method looks like this
func saveData(_ data: Any?) {
self.data = data
}
The table is not updated when the Switch is changed but as the class deals with only one row action at a time, I'm unsure how to update the TableView from the custom Switch class
This would be the responsibility of the controller that is setting the switchAction of each cell.
When the switchAction closure is called, the provider of the closure must update its data model as needed and reload the table view.
You need to update your switchAction in cellForRowAt to something like this:
cell.switchAction = { isOn in
thisRow.saveData(isOn)
// This switch is on, reset all of the other row data
if isOn {
for (index, row) in rowData.enumerated() {
if index != indexPath.row && row.type == .switch {
row.saveData(false)
}
}
tableView.reloadData()
}
}

Pass value to next view when label in Table view cell is tapped

would love to pass the value postArray[indexpath.row].creatorId when the label inside a tableview cell is tapped so it can be passed onto the next view controller so i can load the profile of that particular creator/user. I used custom cells, so how do i get the creator id based on the location of the label(username) selected.
//custom cell
class PostCell : UITableViewCell
{
#IBOutlet weak var timeAgoLabel: UILabel!
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var profileImageView: UIImageView!
#IBOutlet weak var postImageView: UIImageView!
#IBOutlet weak var captionLabel: UILabel!
#IBOutlet weak var postStatsLabel: UILabel!
}
//do something when label is tapped
#objc func tapFunction(sender:UITapGestureRecognizer) {
//userClicked = creatorData
print(userClicked)
appDelegate.profileView()
print("tap working")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 1
}else{
return postsArray.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//var returnCell: UITableViewCell!
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! statusCell
profilePicture = UserDefaults.standard.object(forKey: "userPic") as? String
if profilePicture != nil {
//load profile picture from library
let urlString = "https://test.com/uploads/profile-picture/"+(profilePicture)!
let profileURL = URL(string: urlString)
cell.statusProfilePic?.downloadedFrom(url: profileURL!)
} else {
print("you have no profile picture set")
}
return cell
} else {
if postsArray[indexPath.row].photos != nil{
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
if postsArray[indexPath.row].comments != nil {
comments = postsArray[indexPath.row].comments?.count
} else {
comments = 0
}
if postsArray[indexPath.row].like_list != nil {
likes = postsArray[indexPath.row].like_list?.count
}else{
likes = 0
}
//assign post id to PostID
postID = postsArray[indexPath.row].post_id
//make username clickable!
let tap = UITapGestureRecognizer(target: self, action: #selector(NewsfeedTableViewController.tapFunction))
cell.usernameLabel.isUserInteractionEnabled = true
cell.usernameLabel.addGestureRecognizer(tap)
cell.usernameLabel.text = postsArray[indexPath.row].fullname
cell.timeAgoLabel.text = postsArray[indexPath.row].data_created
cell.captionLabel.text = postsArray[indexPath.row].content
cell.timeAgoLabel.text = postsArray[indexPath.row].modified
//15 Likes 30 Comments 500 Shares
cell.postStatsLabel.text = "\(likes!) Likes \(comments!) Comments"
//load profile picture from library
let urlString = "https://test.com/uploads/profile-picture/"+(postsArray[indexPath.row].profile_pic_filename)!
let profileURL = URL(string: urlString)
cell.profileImageView.downloadedFrom(url: profileURL!)
//iterate through posts images images array
//load post picture from server library
var postImageName : String?
if postsArray[indexPath.row].photos != nil{
let postImage = postsArray[indexPath.row].photos
for postsImage in postImage!{
postImageName = postsImage.filename!
}
let urlPostImageString = "https://test.com/uploads/post-picture/"+(postImageName)!
let postsImageUrl = URL(string: urlPostImageString)
cell.postImageView.downloadedFrom(url: postsImageUrl!)
} else {
print("Post has no picture")
}
//return cell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoImageCell", for: indexPath) as! NoImageTableViewCell
if postsArray[indexPath.row].comments != nil {
comments = postsArray[indexPath.row].comments?.count
} else {
comments = 0
}
if postsArray[indexPath.row].like_list != nil {
likes = postsArray[indexPath.row].like_list?.count
} else {
likes = 0
}
//make username clickable!
let tap = UITapGestureRecognizer(target: self, action: #selector(NewsfeedTableViewController.tapFunction))
cell.noImageUsername.isUserInteractionEnabled = true
cell.noImageUsername.addGestureRecognizer(tap)
cell.noImageUsername.text = postsArray[indexPath.row].fullname
cell.noImageTime.text = postsArray[indexPath.row].data_created
cell.noImagePost.text = postsArray[indexPath.row].content
cell.noImageTime.text = postsArray[indexPath.row].modified
//15 Likes 30 Comments 500 Shares
cell.noImageLikeAndComment.text = "\(likes!) Likes \(comments!) Comments"
//load profile picture from library
let urlString = "https://test.com/uploads/profile-picture/"+(postsArray[indexPath.row].profile_pic_filename)!
let profileURL = URL(string: urlString)
cell.noImageProfilePic.downloadedFrom(url: profileURL!)
return cell
}
}
}
Use this for example.
Implement didSelectRow() method and in it write something like this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// this method works, when you taped cell. write here code of you need. Next code only example, which set user info to some VC and push it:
let controller = UserController as? UserController
if let controller = controller {
controller.user = users[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
}
add this to your Cell's class:
func setTap() {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapRecognized))
self.label.addGestureRecognizer(tap)
tap.numberOfTapsRequired = 1
}
#objc func tapRecognized(sender: UITapGestureRecognizer) {
// here your code of tap on label
print("label tapped")
}
Check on storyBoard is your label isUserInteractionEnabled? - set it to true. Inside tapRecodnized() method do what are you need. And you need to call method setTap() in your cell's method, which you call in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell.
Update
Simple example. this code know what are you tapped. if you tap cell, but not label, add code of push some controller, else code of push another controller.
Cell's Class:
class MyTableViewCell: UITableViewCell {
#IBOutlet weak var label: UILabel!
var mainController: ViewController?
func setText(text: String) {
setTap()
label.text = text
}
func setTap() {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapRecognized))
self.label.addGestureRecognizer(tap)
tap.numberOfTapsRequired = 1
}
#objc func tapRecognized(sender: UITapGestureRecognizer) {
if let mainController = mainController {
print("label tapped")
mainController.pushSomeVc(cell: self)
}
}
}
Code of main Class:
class ViewController: UIViewController {
#IBOutlet weak var myTableView: UITableView!
var array = ["1", "2", "3", "4", "5", "6"]
override func viewDidLoad() {
super.viewDidLoad()
}
func pushSomeVc(cell: MyTableViewCell) {
let row = myTableView.indexPath(for: cell)?.row
if let row = row {
// write here code of push controller, when label tapped. row property for get some user from array
print("push some vc with \(row)")
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "cell") as? MyTableViewCell
if let cell = cell {
cell.setText(text: array[indexPath.row])
cell.mainController = self
}
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
// write here code of push controller with comments
print("cell tapped: \(indexPath.row)")
}
}
I tested this code and it's work perfect

Resources