using indexPath from table row in outside function swift - ios

New to swift and for a uni project but i have a table view which holds a record of friends details
The user can have the option to edit a friend or delete a friend.
to do this i created a long tap gesture for delete a friend but i am unsure how to pass the indexPath to the function
this is my current layout:
import UIKit
class view_19342665: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var friends: [Friends] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "friends", for: indexPath)
cell.textLabel?.adjustsFontSizeToFitWidth = true;
cell.textLabel?.font = UIFont.systemFont(ofSize: 13.0)
cell.textLabel?.text = friends[indexPath.row].displayInfo
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let id = friends[indexPath.row].studentID
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.removeRecord(id: Int(id))
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
let appDelegate = UIApplication.shared.delegate as! AppDelegate
friends = appDelegate.getFriendInfo()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(sender:)))
tableView.addGestureRecognizer(longPress)
self.tableView.rowHeight = 33.0
}
override var canBecomeFirstResponder: Bool{
return true
}
#objc func handleLongPress(sender:UILongPressGestureRecognizer ){
if sender.state == .began{
// delete user
}
else{
//edit user
}
}
}
right now i can delete the row in the table function.
this is what i am trying to achieve:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let id = friends[indexPath.row].studentID
handleLongPress(id)
}
func handleLongPress(id : Int){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if sender.state == .began{
appDelegate.removeRecord(id: Int(id))
}
else{
appDelegate.editRecord(id: Int(id))
}
can someone please help me delete a row using the ID on a long tap gesture

The gesture should be added to the table cells inside cellForRowAt not to the table itself
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
cell.contentView.addGestureRecognizer(longPress)
cell.contentView.tag = indexPath.row
Then
#objc func handleLongPress(_ tap:UILongPressGestureRecognizer) {
guard tap.state == .ended && let index = tap.view?.tag else { return }
// use index
}

Related

Swift make wishlist feature

so I want to make this simple wishlist feature for when the user tapped the "heart" button it will add that data from view to wishlist view. just like this :
so when the user tapped that heart button, that movie will show in this wishlist view like this :
now, my question is how do I notify my wishlistVc so that it knows there's a new "wishlist" that the user tapped from the movie list. I have an idea that I should use a delegate, but still, I can't figure out how to implement a delegate in this case.
and I use "var movieList" to store all the data in HomeVc, and my idea is when the user tapped that heart button in tableview, that data that user tapped with will move into my "let wishlist", so i can populate it on my wishlistVC ( but I don't know how to do this so I need help)
so far this is my code :
class DefaultTableViewCell: UITableViewCell {
#IBOutlet weak var moviePosterImage: UIImageView!
#IBOutlet weak var movieTitleLabel: UILabel!
#IBOutlet weak var wishlistButton: UIButton!
var indexPath: IndexPath!
var delegate: DefaultTableViewDelegate?
var wishlistFlag:Bool = false
override func layoutSubviews() {
super.layoutSubviews()
wishlistButton.titleLabel?.text = ""
wishlistButton.addTarget(self, action: #selector(wishlistTapped(_:)), for: .valueChanged)
}
#IBAction func wishlistTapped(_ sender: UIButton) {
wishlistFlag = !wishlistFlag
delegate?.wishlistTrigger(row: indexPath.row)
if wishlistFlag == true {
wishlistButton.setImage(UIImage(named: "heart_fill"), for: .normal)
}else if wishlistFlag == false {
wishlistButton.setImage(UIImage(named: "heart"), for: .normal)
}
}
}
HomeVc (the vc that shows the movie list):
var movieList : [Movie] = []
extension HomeVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movieList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = movieList[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultTableViewCell", for: indexPath) as! DefaultTableViewCell
cell.indexPath = indexPath
cell.movieTitleLabel.text = data.title
cell.moviePosterImage.sd_setImage(with: data.imageUrl)
cell.delegate = self
return cell
}
}
protocol DefaultTableViewDelegate {
func wishlistTrigger(row: Int)
}
this is my wishlistVc:
let wishlist : [Movie] = []
extension WishlistVc: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wishlist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = wishlist[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultTableViewCell", for: indexPath) as! DefaultTableViewCell
cell.movieTitleLabel.text = data.title
cell.moviePosterImage.sd_setImage(with: data.imageUrl)
cell.wishlistButton.titleLabel?.text = ""
cell.indexPath = indexPath
return cell
}
}
I've been stuck for 2 whole days now I still don't know how to figure this out. I appreciate anyone that can help me. Thanks
Implement func like:
func wishlistTrigger(row: Int) {
self.myWishlistedItem.append(self.movieList[row]) //Add that wishlisted item in array
self.tableView.reloadData() //Now reload Table
}

How to load a second array into the UITableView when I swipe left by using Swift 4.2 and iOS12?

I just started learning Swift programming.
When the app opens, I am loading an array into the UITableView.
However, when the user Swipes left, the same UITableView should load the second array and he is Swipes right, the UITableView should load the first array again.
I have tested the following code, it changes the colors according to the Swipes. however, I am unable to load the second array.
override func viewDidLoad() {
super.viewDidLoad()
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
view.addGestureRecognizer(rightSwipe)
}
#objc func handleSwipe(sender: UISwipeGestureRecognizer) {
if sender.state == .ended {
switch sender.direction {
case .right:
view.backgroundColor = .red
print("Right swipe")
let newCell = goNext(tblView, cellForRowAt: idxPath)
print(newCell)
}
func goNext(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "chapterCell", for: idxPath)
if currentChapter != totalChapters[0] {
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = genCh2[indexPath.row]
}
return cell
}
Two things: You need a tableView datasource and the swipe gestures have a direction and need to be set.
class MyViewController : UIViewController , UITableViewDataSource{
var tblView : UITableView!
var genCh1 = ["first","second","later"]
var genCh2 = ["data","data1","data2"]
var currentData : [String]?
//TableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentData?.count ?? 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "chapterCell", for: indexPath)
//if currentChapter != totalChapters[0] {
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = currentData?[indexPath.row]
// }
return cell
}
func reloadData(_ array : [String]){
currentData = array
tblView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
// setup viewController
super.viewDidAppear(animated)
tblView = UITableView.init(frame: view.bounds)
tblView.backgroundColor = .red
view.addSubview(tblView)
tblView.dataSource = self
tblView.register(UITableViewCell.self, forCellReuseIdentifier: "chapterCell")
reloadData(genCh1)
//add gesture
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
rightSwipe.direction = .right
view.addGestureRecognizer(rightSwipe)
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
leftSwipe.direction = .left
view.addGestureRecognizer(leftSwipe)
}
#objc func handleSwipe(sender: UISwipeGestureRecognizer) {
if sender.state == .ended {
switch sender.direction {
case .right:
view.backgroundColor = .red
print("Right swipe")
reloadData(genCh1)
case .left:
view.backgroundColor = .blue
print("Left swipe")
reloadData(genCh2)
default:
break;
}}}
}
I think your confusion stems from how UITableViewControllers work with respect to displaying and updating data. Ultimately, it is the responsibility of the UITableView data source to provide the correct data for display. You don't want to directly update a cell. Rather you ask the tableview to reload and then make sure the appropriate data source method will provide the data you want (in this case cellForRowAt is the method we are most interested in). I have something that essentially does what you wanted which will hopefully get you started in the right direction.
Its not 100% as you described as left swipes are generally used by the table view to indicate that the user is trying to delete the cell. As the example is written below, the left swipes will never register. So long term using swipe gestures as you describe might not be the best choice.
class TableViewController: UITableViewController {
let dataArray1 = ["1", "2", "3"]
let dataArray2 = ["red", "blue", "green"]
var activeArray = 1
override func viewDidLoad() {
super.viewDidLoad()
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
view.addGestureRecognizer(rightSwipe)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseId", for: indexPath)
cell.textLabel?.text = activeArray == 1 ? dataArray1[indexPath.row] : dataArray2[indexPath.row]
return cell
}
#objc func handleSwipe(_ sender: UISwipeGestureRecognizer) {
if sender.state == .ended {
switch sender.direction {
case .right:
self.activeArray = 2
self.tableView.reloadData()
case .left:
self.activeArray = 1
self.tableView.reloadData()
default:
break
}
}
}
}

UISwitch state in Tableviewcell resets when user scrolls - Swift

I've searched for a solutions on this issue but none seem to work for my use case.
I have a table inside a viewcontroller and the issue I am facing is that when scrolling the UISwitch state is reset to OFF. I understand table cells are reused, but how do I implement a solution that will restore the state of UISwitch when a user scrolls based on my code below
import UIKit
class StirrViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var mylabel: UILabel!
var myString = String()
#IBAction func stirrBtn(_ sender: AnyObject) {
}
var timeSelected = String()
var selectedTimeArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
mylabel.text = myString
self.timeSelected = myString
}
func switchChanged(_ sender : UISwitch!){
print("table row switch Changed \(sender.tag)")
print("The switch is \(sender.isOn ? "ON" : "OFF")")
let kValue = (sender.tag + 1)
let keyValue = String(kValue)
if sender.isOn {
recipeSettings.boolStirrSwitch[keyValue] = true
recipeSettings.switchedOnArr.append(keyValue)
} else {
recipeSettings.boolStirrSwitch[keyValue] = false
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let stringNum = Int(self.timeSelected)
recipeSettings.recipeTimeSet2 = stringNum!
return(stringNum)!
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell
//here is programatically switch make to the table view
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell.accessoryView = switchView
// Process data displayed in rows(minutes)
let endTime = Int(self.timeSelected)
let startTime = Int(1)
// Recipe time array
let timeArray: [Int] = Array(startTime...endTime!)
let stringTimeArr = timeArray.map{String($0)}
// Save time array to global variable
recipeSettings.recipeTimeSetArr = stringTimeArr
// Create a boolean Array to hold all default false booleans
let defBool: Bool = false
var defBoolArr: [Bool] = []
// Fill the array with the defaults boolean
for _ in 0..<stringTimeArr.count{defBoolArr.append(defBool)}
// Map the array to global dictionary containing the Time in an array and default "false" value
for i in 0..<stringTimeArr.count {
recipeSettings.boolStirrSwitch[stringTimeArr[i]] = defBoolArr[i]
}
// Add the minutes to cell table
cell.textLabel?.text = stringTimeArr[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
As you can see in my code I do save the state of each UI switch in a global variable dictionary. How can I solve the issue of UISwitch changing states based on this code? All help is appreciated. Thanks in advance
var switchState = [String : Bool]()
your recipeSettings.boolStirrSwitch should be decleard like that.
As you are using timeSelected as numberOfRowsInSection as showing
your cell.textLabel from that so you don't need extra stringTimeArr
for that.
All the processing you do in cellForRowAt it will happen again and
again table cells are reused so for setting up data do it in another
function then reload TableView.
Solution for your problem should be look like that.
import UIKit
class StirrViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
//make tableView IBOutlet for reloading data
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var mylabel: UILabel!
var myString = String()
#IBAction func stirrBtn(_ sender: AnyObject) {
}
var timeSelected = String()
var selectedTimeArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
mylabel.text = myString
self.timeSelected = myString
self.setdefaultSwitchState()
}
//recipeSettings.boolStirrSwitch should be decleard like that
var switchState = [String : Bool]()
//setDeaultSwitchState
func setdefaultSwitchState(){
if let timeSelected = Int(self.timeSelected){
for value in 0..<timeSelected{
switchState["\(value)"] = false
//or
//recipeSettings.boolStirrSwitch["\(value)"] = false
}
}
self.tableView.reloadData()
}
#objc func switchChanged(_ sender : UISwitch!){
print("table row switch Changed \(sender.tag)")
print("The switch is \(sender.isOn ? "ON" : "OFF")")
let kValue = (sender.tag + 1)
let keyValue = String(kValue)
if sender.isOn {
switchState[keyValue] = true
} else {
switchState[keyValue] = false
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let stringNum = Int(self.timeSelected)
recipeSettings.recipeTimeSet2 = stringNum!
return(stringNum)!
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell
//here is programatically switch make to the table view
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell.accessoryView = switchView
cell.textLabel?.text = "\(indexPath.row + 1)"
if let switchState = switchState["\(indexPath.row)"] {
if switchState{
switchView.isOn = true
}else{
switchView.isOn = false
}
}else{
switchView.isOn = false
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

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

Delegate always nil in tableviewcontroller

I am trying to pass data from my tableViewController to my ProfileViewController. so when i clicked cell, then my profile textfield will set the text to the cell that i clicked before.
This is my TableViewController .
protocol TableViewDelegate {
func clickedTableViewCell(info: String)
}
class ProfilePlaceTableViewController : UITableViewController {
var delegate: TableViewDelegate!
#IBOutlet var tableViewProfile: UITableView!
let foods = ["tomato", "red", "rice", "milk", "cheese"]
override func viewDidLoad() {
super.viewDidLoad()
tableViewProfile.delegate = self
tableViewProfile.dataSource = self
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foods.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = foods[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (tableView.cellForRow(at:indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark) {
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
} else {
tableView.cellForRow(at:indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
}
//getting the index path of selected row
let indexPath = tableView.indexPathForSelectedRow
//getting the current cell from the index path
let currentCell = tableView.cellForRow(at: indexPath!)! as UITableViewCell
//getting the text of that cell
let currentItem = currentCell.textLabel!.text
print("currentItem : ", currentItem!)
if (delegate != nil) {
self.delegate?.clickedTableViewCell(info: currentItem!)
self.dismiss(animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
This is my profileViewController .
class ProfileViewController : UIViewController, TableViewDelegate {
#IBOutlet weak var provinceText: kTextFiledPlaceHolder!
var profilePlaceTableViewController = ProfilePlaceTableViewController()
func clickedTableViewCell(info: String) {
provinceText.text = info
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showProfilePlace" {
let showProfileVc: ProfilePlaceTableViewController = segue.destination as! ProfilePlaceTableViewController
showProfileVc.delegate = self
}
}
override func viewDidLoad() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "ic_hamburger_menu"), for: UIControlState.normal)
button.setTitleColor(UIColor.black, for: .normal)
button.addTarget(self.revealViewController(), action:#selector(SWRevealViewController.revealToggle(_:)), for: UIControlEvents.touchUpInside)
button.sizeToFit()
button.imageEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
provinceText.addTarget(self, action: #selector(provinceClicked(_:)), for: .touchDown)
profilePlaceTableViewController.delegate = self
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func provinceClicked(_ textField: UITextField) {
performSegue(withIdentifier: "showProfilePlace", sender: nil)
}
I have done all this and follow many tutorials but still no solution. Any help would be appreciated. Thank you.
You've declared your delegate (TableViewDelegate) as non-optional, but in the didSelect method, you're using optional chaining - self.delegate?.clickedTableViewCell(info: currentItem!)
Declare your delegate as weak optional property - weak var delegate: TableViewDelegate? = nil to avoid retain cycle.
Delete your profilePlaceTableViewController.delegate = self. You're doing the same in your performSegue method.
And change your protocol declaration to:
protocol TableViewDelegate: class {
func clickedTableViewCell(info: String)
}

Resources