DidSelectRow is not working - ios

Pretty much what the title says: DidSelectRow is not getting called, and I did check that I didn't use Deselect. I also checked that delegate and DataSource are connected to the tableViewController and the Selection was Single Selection. However, the method is still not getting called.
Does an empty tableView might have any effect to it(reason it's empty is because the user starts to populate it. I'm using CoreData for it)?
EDIT
This is what the method looks like:
var effectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
var effect: UIVisualEffect!
let defaults = UserDefaults.standard
var userMagazineTitle = [User]()
var dataString = String()
override func viewDidLoad() {
super.viewDidLoad()
addProgrammatically()
let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
do{
let users = try PresistanceService.context.fetch(fetchRequest)
self.userMagazineTitle = users
self.tableView.reloadData()
}catch{
ProgressHUD.showError("Nothing to see here")
}
}
/ MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userMagazineTitle.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyFeedTableViewCell
cell.myHeadline?.text = userMagazineTitle[indexPath.row].title
cell.indentationLevel = 3
return cell
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let manage = PresistanceService.persistentContainer.viewContext
let del = userMagazineTitle[indexPath.row]
if editingStyle == .delete {
// Delete the row from the data source
manage.delete(del)
do{
try manage.save()
}catch{
ProgressHUD.showError()
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do{
userMagazineTitle = try manage.fetch(fetchRequest) as! [User]
}catch{
ProgressHUD.showError()
}
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "showUser", sender: indexPath)
navigationController?.navigationBar.isHidden = false
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showUser" {
let DestViewController = segue.destination as! UINavigationController
let targetController = DestViewController.topViewController as! CompanyTableViewController
let indexPath = sender as! IndexPath
let user = userMagazineTitle[indexPath.row].title
let user2 = userMagazineTitle[indexPath.row].rssurl
targetController.customUserInit(articlesindex: indexPath.row, title: user!, rssUrl: user2!)
}
}
func addProgrammatically() {
effectView.frame = view.bounds
tableView.addSubview(effectView)
effectView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
effectView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
} else {
// Fallback on earlier versions
effectView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
}
effectView.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true
effectView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
effect = effectView.effect
effectView.effect = nil
self.tableView.separatorStyle = .none
tableView.backgroundView = UIImageView(image: UIImage(named: "myMagazines.jpg"))
tableView.backgroundView?.contentMode = .scaleAspectFill
tableView.clipsToBounds = true
navigationController?.navigationBar.isHidden = false
UIApplication.shared.statusBarStyle = .lightContent
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
}
}

Another thing that might lead to the issue is not selected selection kind. I lost my two hours for fixing this.
Cross check cell selection , if it is selected for no selection change it to single selection.
To do this programatically :
Swift : tableView.allowsSelection = YES;
Objective C: [tableView allowsSelection : YES];
==============================
This might be helpful to someone!

You have added a UIVisualEffectView view on top of tableview, which is not passing the touch events to tableview.
Setting effectView.isUserInteractionEnabled = false, should make this view pass touch events to the views underneath.

There could be two issues for this problem:
The method signature of the TableView DidSelectRow could be wrong. The current signature is:
Swift:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
ObjectiveC: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
You are setting the Delegate of the TableView to nil somewhere in the code.

Related

Remove row from table view

How can I remove row from tableview cell I cant remove the cell from table view I don't know why and when I try to delete never gone from table view please someone tell me how I can delete it one cell from multiple cell I have it. I know I should have var but I did not put it for example var = something
class addCartTblVC: UITableViewController {
//MARK: -Variables
var coreDataVariables = GetCoreDataVariables()
//MARK: -ViewMethords
override func viewDidLoad() {
super.viewDidLoad()
self.fetchCart()
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem
tableView.tableFooterView = UIView()
}
//MARK: -tableView dataSource
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return coreDataVariables.result_add_Cart.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cartCell = tableView.dequeueReusableCell(withIdentifier: "cartCell", for: indexPath) as! AddCartTblCell
let img = coreDataVariables.result_add_Cart[indexPath.row].product_Image!
let userPhotoString = img
let imageUrl:URL = URL(string: userPhotoString)!
let imageData:Data = try! Data(contentsOf: imageUrl)
// Add photo to a cell as a subview
if let image = UIImage(data: imageData){
cartCell.pro_Img.image = image
}
cartCell.pro_MRP.text = coreDataVariables.result_add_Cart[indexPath.row].product_Price
cartCell.pro_Details.text = coreDataVariables.result_add_Cart[indexPath.row].product_Name
cartCell.pro_Discount.text = coreDataVariables.result_add_Cart[indexPath.row].product_Discount
if cartCell.pro_Discount.text! == cartCell.pro_MRP.text!{
cartCell.pro_Discount.isHidden = true
cartCell.crossView.isHidden = true
}
else{
cartCell.pro_MRP.textColor = UIColor.darkGray
cartCell.pro_Discount.isHidden = false
cartCell.crossView.isHidden = false
}
cartCell.proceedBtn.tag = indexPath.row
cartCell.proceedBtn.addTarget(self, action: #selector(addCartTblVC.ProceedTapped(_:)), for: .touchUpInside)
cartCell.removeFromCoreDataBtn.tag = indexPath.row
cartCell.removeFromCoreDataBtn.addTarget(self, action: #selector(addCartTblVC.deleteFromCart(_:)), for: .touchUpInside)
return cartCell
}
//MARK: -fetchFunction
func fetchCart(){
let cart = Add_Cart()
coreDataVariables.result_add_Cart = cart.fetchCart()!
}
//MARK: -Proceed Action
#IBAction func back(_ sender: UIBarButtonItem) {
dismiss(animated: false, completion: nil)
}
Before loading table data try to loop on coreDataVariables.result_add_Cart and check for duplicate elements and try to make them single element by multiplying product_Price * n of duplicates and take care of product_Discount also.
your approach should be like this ((this method only for removing duplicates)) :
extension Array where Element: Equatable {
mutating func removeDuplicates() {
var result = [Element]()
for value in self {
if !result.contains(value) {
result.append(value)
}
}
self = result
}
==> Hope not getting negative vote for this answer :D

Cosmic Mind - How to resize view when TabsController is implemented

I am having a problem on inserting a title to this screen.
How can I resize this view?
Here's my code where the TabsController is implemented:
class DashboardViewController: TabsController {
let screenSize = UIScreen.main.bounds
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare() {
super.prepare()
tabBar.lineColor = UIColor.CustomColor.blue
tabBar.setTabItemsColor(UIColor.CustomColor.grey, for: .normal)
tabBar.setTabItemsColor(UIColor.CustomColor.blue, for: .selected)
tabBarAlignment = .top
tabBar.tabBarStyle = .auto
tabBar.dividerColor = nil
tabBar.lineHeight = 2.0
tabBar.lineAlignment = .bottom
tabBar.backgroundColor = .white
}
}
Here's my option one code (and the option two code is the same):
class TeamProjectViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
prepareTabItem()
setupTableView()
}
fileprivate func setupTableView() {
tableView.backgroundColor = .white
tableView.allowsSelection = false
tableView.separatorColor = UIColor.CustomColor.lightGrey
tableView.register(UINib(nibName: "ProjectTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProjectTableViewCell
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
}
extension TeamProjectViewController {
fileprivate func prepareTabItem() {
tabItem.title = "Option 1"
}
}
And here's what's happening to my tabs:
Thank you!
In your code you do not have anywhere where you are actually setting a view over the TabsController, where a title could exist. You would need to wrap the TabsController in order to accomplish this. One way, is use a ToolbarController:
let toolbarController = ToolbarController(rootViewController: myTabsController)
toolbarController.toolbar.title = "my title"
This is one way of going about your issue.
If you want just 20 pixels to move the tabs below status bar you can use StatusBarController with displayStyle = .partial. That's how I workaround.
let tabsController = TabsController(viewControllers: [
MyViewController1(),
MyViewController2()
])
let statusBarController = StatusBarController(rootViewController: tabsController)
statusBarController .displayStyle = .partial
// add statusBarController to hierarchy

Value of type '_' has no member

In the cb.check(self.rowChecked[indexPath.row]) line under cellForRowAt I'm getting a "Value of type 'LolFirstTableViewController' has no member 'rowChecked'" even though I set up rowChecked to be an array of Booleans with tasks.count number of items. Do I need to initialize rowChecked somewhere else besides cellForRowAt or what am I doing wrong here? The point of this code is to make a checkbox show up in each cell of a table where you can click it to change the accessory to a check mark, and click it again to uncheck it. The check box itself is a separate custom class called CheckButton. I'm still learning Swift so any help would be greatly appreciated! Thank you!
import UIKit
class LoLFirstTableViewController: UITableViewController {
var tasks:[Task] = taskData
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 60.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
#IBAction func cancelToLoLFirstTableViewController(_ segue:UIStoryboardSegue) {
}
#IBAction func saveAddTask(_ segue:UIStoryboardSegue) {
if let AddTaskTableViewController = segue.source as? AddTaskTableViewController {
if let task = AddTaskTableViewController.task {
tasks.append(task)
let indexPath = IndexPath(row: tasks.count-1, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
let task = tasks[indexPath.row]
cell.task = task
var rowChecked: [Bool] = Array(repeating: false, count: tasks.count)
if cell.accessoryView == nil {
let cb = CheckButton()
cb.addTarget(self, action: #selector(buttonTapped(_:forEvent:)), for: .touchUpInside)
cell.accessoryView = cb
}
let cb = cell.accessoryView as! CheckButton
cb.check(self.rowChecked[indexPath.row])
return cell
}
func buttonTapped(_ target:UIButton, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
let point = touch.location(in: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: point)
var tappedItem = tasks[indexPath!.row] as Task
tappedItem.completed = !tappedItem.completed
tasks[indexPath!.row] = tappedItem
tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)
}
You are declaring rowChecked as a local variable and calling it with self.rowChecked as if it were a class property.
To solve this issue, remove the self. before rowChecked.
Old:
cb.check(self.rowChecked[indexPath.row])
New:
cb.check(rowChecked[indexPath.row])
There might be further issues, but that's the reason for the error as your code currently stands.
You have the line: var rowChecked: [Bool] = Array(repeating: false, count: tasks.count) inside the tableView:cellForRowAt method, so it's a local variable, it's not a property of the LolFirstTableViewController class.
That means you need to change this line: cb.check(self.rowChecked[indexPath.row]) to cb.check(rowChecked[indexPath.row]) (Removed self.).

Searching TableView can't select row

While searching a tableView, every time I try to select a row it just takes me back to the unsearched tableView. What am I missing? the segue works perfectly when not filtering through the table. The ability to select a row just disapears while the searchBar is activated.
import UIKit
import Foundation
class BenchmarkWODViewController: UITableViewController, UISearchResultsUpdating {
var WodList = [WOD]()
var FilteredWodList = [WOD]()
var Keyword = ""
var searchController : UISearchController?
var index = Int()
#IBAction func backButton(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
override func viewDidLoad() {
super.viewDidLoad()
for wodData in BenchmarkWODs.library {
let wod = WOD(dictionary: wodData)
WodList.append(wod)
}
// Search Bar
self.searchController = UISearchController(searchResultsController: nil)
self.searchController?.searchBar.autocapitalizationType = .None
self.tableView.tableHeaderView = self.searchController?.searchBar
self.searchController?.searchResultsUpdater = self
self.Keyword = ""
definesPresentationContext = true
self.filterByName()
}
func filterByName(){
self.FilteredWodList = self.WodList.filter({ (wod: WOD) -> Bool in
if self.Keyword.characters.count == 0 {
return true
}
if (wod.name?.lowercaseString.rangeOfString(self.Keyword.lowercaseString)) != nil {
return true
}
return false
})
self.tableView.reloadData()
}
// Search Bar Function
func updateSearchResultsForSearchController(searchController: UISearchController) {
Keyword = searchController.searchBar.text!
self.filterByName()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.FilteredWodList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("BenchmarkCell", forIndexPath: indexPath) as UITableViewCell
let wod = self.FilteredWodList[indexPath.row]
if let wodName = wod.name {
cell.textLabel?.text = wodName
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.filterByName()
self.performSegueWithIdentifier("showBenchmarkDetail", sender: nil)
}
}
Figured it out after playing around. Apparently adding the below code corrects the problem.
searchController?.dimsBackgroundDuringPresentation = false
swift 'dimsBackgroundDuringPresentation' was deprecated in iOS 12.0 Use the obscuresBackgroundDuringPresentation property instead.
searchController?.obscuresBackgroundDuringPresentation = false
searchController.obscureBAckgroundDuringPresentation = false is deprecated in IOS 12.0, so for me it was issue with other gesture detector added to the tableview , so make sure you dont have any other gesture detector and touchesview method that distort the normal working flow of tablview's delegate method( didSelectAtRow ), hope it will work,

Two UITableView in single UIViewcontroller not working properly

I want to implement following functionality in app show pict
But i have following problem show another pict
my code as follow
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if str == "Loading"{
return 0
}else if tableView == tbl2{
return arrSub.count
}else{
return self.displayData.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCellInvitation = self.tableView.dequeueReusableCellWithIdentifier("cell")as! customCellInvitation
if tableView == tbl2{
//Code for the load secind table
cell.lblUserName.text = self.arrSub.objectAtIndex(indexPath.row).valueForKey("username") as?String
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
return cell
}else{
//Code for the load first table
cell.lblUserName.text = self.displayData.objectAtIndex(indexPath.row).valueForKey("username") as?String
cell.btnAdd.setImage(UIImage(named: "add.png"), forState:(UIControlState.Normal))
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Selected))
cell.btnAdd.addTarget(self, action: "addData:", forControlEvents: .TouchUpInside)
cell.btnAdd.tag = indexPath.row
}
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
//function call when user click Plus button
func addData(sender: UIButton!) {
arrSub .addObject(self.displayData .objectAtIndex(sender.tag))
var button:UIButton = sender.viewWithTag(sender.tag) as! UIButton
button.selected=true
button.userInteractionEnabled = false
NSLog("%#", arrSub)
[tbl2 .reloadData()]
}
I would suggest you to move your tableView Datasource and Delegate to separate classes. This is not a good practise at all. You will certainly mess up with your code.
What you are doing make code complexity, you can add you own custom class for tableView and can maintain it it all delegate datasource methods.Add that tableview in current class and with giving frame to it. By this you can add as many number of tableview to a single class and no need to worry about data handling.
Put a frame to this table view, then you can add two frame to a view controller. So add this frame to your view controller, you should adjust the frame width and hight in order to show two tables.
class ViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(20, (self.view.frame.size.height - 54 * 5) / 2.0, (self.view.frame.size.width - 25 * 5), 54 * 5)
tableView.autoresizingMask = .FlexibleTopMargin | .FlexibleBottomMargin | .FlexibleWidth
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
tableView.showsVerticalScrollIndicator = true
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension LeftMenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let titles: [String] = ["Home", "Features", "Pricing", "Help", "About Us", "Contact Us"] // put your titles
let images: [String] = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty", "IconEmpty"] // add images if you want
cell.backgroundColor = UIColor.clearColor() // optional
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
cell.imageView?.image = UIImage(named: images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TabBar") as! UIViewController
sideMenuViewController?.contentViewController = viewController
sideMenuViewController?.hideMenuViewController()
break // show table navigation view controller
case 1:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TabBar") as! UIViewController
sideMenuViewController?.contentViewController = viewController
sideMenuViewController?.hideMenuViewController()
break // show table navigation view controller
default:
break
}
}
}
// MARK: UITextFieldDelegate Methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCellInvitation = self.tableView.dequeueReusableCellWithIdentifier("cell")as! customCellInvitation
if tableView == tbl2{
cell.lblUserName.text = self.arrSub.objectAtIndex(indexPath.row).valueForKey("username") as?String
if str = "yes"{
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
}else{
cell.btnAdd.setImage(UIImage(named: "NO.png"), forState:(UIControlState.Normal))
}
return cell
}else{
cell.lblUserName.text = self.displayData.objectAtIndex(indexPath.row).valueForKey("username") as?String
if str = "yes"{
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
}else{
cell.btnAdd.setImage(UIImage(named: "NO.png"), forState:(UIControlState.Normal))
}
}
return cell
}

Resources