How to slide out the side menu bar when I swipe to the left? and how will it automatically slide out when I click the collectionView? I'm using tableView and constraints, my outlet to that constraint is rightMargin.
import UIKit
import ViewPagerController
class OptionTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var rightMargin: NSLayoutConstraint!
#IBOutlet weak var optionTableView: UITableView!
let option = ["LOG IN","SIGN UP","EDIT PROFILE", "LOG OUT"]
let storyBoardId = ["LogInViewController","SignUpViewController","UserEditPageViewController", "None"]
override func viewDidLoad() {
super.viewDidLoad()
var appearance = ViewPagerControllerAppearance()
appearance.tabMenuAppearance.backgroundColor = UIColor.black
let screenWidth = UIScreen.main.bounds.width
rightMargin.constant = screenWidth
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.rightMargin.constant = 100
UIView.animate(withDuration: 0.3 , animations: {
self.view.layoutIfNeeded()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return option.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = optionTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = option[indexPath.row]
cell.textLabel?.font = UIFont(name: "Arial", size: 10)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let logInViewController = storyboard?.instantiateViewController(withIdentifier: storyBoardId[indexPath.row]) {
navigationController?.pushViewController(logInViewController, animated: true)
}
}
}
SlideInMenu
These will let you slide to open up your own options.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
print("more button tapped")
}
more.backgroundColor = .lightGray
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
print("favorite button tapped")
}
favorite.backgroundColor = .orange
let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
print("share button tapped")
}
share.backgroundColor = .blue
return [share, favorite, more]
}
Related
I implement in controller, my device testing is iPhone6S iOS 13.3.1, Xcode version is 11.3.1, my project is in Swift 5. when I swipe to left or right sometimes the swipeview move behind cell and cell not move, the custom tableview cell is normal...a view in center with constraint to superview to simulated spaced in cells and willBeginEditingRowAt i change size and y position of nativeview of swipe to have equal height size with simulated spacing cell.
override func viewDidLoad() {
super.viewDidLoad()
self.configtable()
}
private func configtable(){
let tbl = UITableView.init()
self.view.addSubview(tbl)
tbl.register(UINib.init(nibName: "TempcellTableViewCell", bundle: nil), forCellReuseIdentifier: "TempcellTableViewCell")
tbl.translatesAutoresizingMaskIntoConstraints = false
tbl.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10).isActive = true
tbl.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10).isActive = true
tbl.topAnchor.constraint(equalToSystemSpacingBelow: self.view.topAnchor, multiplier: 10).isActive = true
tbl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -10).isActive = true
tbl.delegate = self
tbl.dataSource = self
tbl.backgroundColor = UIColor.gray
self.filltable()
tbl.reloadData()
}
func filltable(){
self.arraypersonas = [persona]()
self.arraypersonas.append(persona.init(ci: 1, nombre: "Person 1"))
self.arraypersonas.append(persona.init(ci: 2, nombre: "Person 2"))
self.arraypersonas.append(persona.init(ci: 3, nombre: "Person 3"))
self.arraypersonas.append(persona.init(ci: 4, nombre: "Person 4"))
self.arraypersonas.append(persona.init(ci: 5, nombre: "Person 5"))
self.arraypersonas.append(persona.init(ci: 6, nombre: "Person 6"))
self.arraypersonas.append(persona.init(ci: 7, nombre: "Person 7"))
}
and tableview delegate functions are:
extension TCViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(#function)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arraypersonas.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110
}
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? TempcellTableViewCell{
if let spvcell = cell.superview{
for svswipe in spvcell.subviews{
let typeview = type(of: svswipe.self)
if typeview.description() == "UISwipeActionPullView"{
svswipe.frame.size.height = 100
svswipe.frame.origin.y = 5
}
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TempcellTableViewCell", for: indexPath) as! TempcellTableViewCell
let item = self.arraypersonas[indexPath.row]
cell.lbltitle.text = "\(item.ci) - \(item.nombre)"
cell.containerbg.backgroundColor = UIColor.white
return cell
}
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let Cancel = UIContextualAction.init(style: .normal, title: "Cancel") { (action, view, nil) in
print("Cancel")
}
Cancel.backgroundColor = UIColor.red
let config = UISwipeActionsConfiguration.init(actions: [Cancel])
config.performsFirstActionWithFullSwipe = false // Prevent swiping
return config
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let Checkin = UIContextualAction.init(style: .normal, title: "Check-in") { (action, view, nil) in
print("Checkin")
}
Checkin.backgroundColor = UIColor.blue
//Checkin.image = UIImage.init(named: Constants.images.iconcheckinhouse)
let Noshow = UIContextualAction.init(style: .normal, title: "No Show") { (action, view, nil) in
print("No show")
}
Noshow.backgroundColor = UIColor.yellow
//Noshow.image = UIImage.init(named: Constants.images.iconthumbsdown)
//arrayactions.append(Cancel)
let config = UISwipeActionsConfiguration.init(actions: [Noshow,Checkin])
config.performsFirstActionWithFullSwipe = false // Prevent swiping
return config
}
In mi Custom TableViewCell have:
class TempcellTableViewCell: UITableViewCell {
#IBOutlet var containerbg: UIView!
#IBOutlet var lbltitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Images Xcode propertys Constraint of subviews TableviewCell
Images of bug:
I have a simple table view showing a list of tasks. I want to show two buttons when user swipes on a cell. A delete button to delete the cell and Completed button to store the task in completed array. I am able to implement the delete button but no idea of showing a second button in the table cell. here is the code.
import UIKit
var taskArray = [String]()
var datesArray = [String]()
class ViewController: UIViewController, UITableViewDataSource
{
#IBOutlet weak var taskTableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return taskArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row + 1). \(taskArray[indexPath.row])"
cell.detailTextLabel?.text = datesArray[indexPath.row]
return cell
}
override func viewDidLoad()
{
super.viewDidLoad()
taskTableView.dataSource = self
let userDefaults = UserDefaults.standard
if let task = userDefaults.stringArray(forKey: "tasks") , let date = userDefaults.stringArray(forKey: "dates")
{
taskArray = task
datesArray = date
}
print(taskArray)
print(datesArray)
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
taskTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
// remove the item from the data model
taskArray.remove(at: indexPath.row)
datesArray.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
//function to come back from close button
#IBAction func close(segue: UIStoryboardSegue)
{
}
}
Swift 4.0
You can write below method of tableView to define custom swipe action.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in
}
delete.backgroundColor = UIColor.red
let complete = UITableViewRowAction(style: .default, title: "Completed") { (action, indexPath) in
// Do you complete operation
}
complete.backgroundColor = UIColor.blue
return [delete, complete]
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
//self.isEditing = false
print("more button tapped")
}
more.backgroundColor = UIColor.lightGray
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
//self.isEditing = false
print("favorite button tapped")
}
favorite.backgroundColor = UIColor.orange
let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
//self.isEditing = false
print("share button tapped")
}
share.backgroundColor = UIColor.blue
return [share, favorite, more]
}
First make this function return true
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
{
return true
}
it makes your cell editable , apple provides default deleting and editing options that you can use as like this :
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if(editingStyle == .delete)
{
myArray.remove(at: indexPath.item)
table.deleteRows(at: [indexPath], with: .automatic)
table.reloadData()
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
if(studentUser as? String == "Admin")
{
return .delete
}
else
{
return .none
}
}
or you can define your custom ones :
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
{
let del = UITableViewRowAction(style: .normal, title: "Delete")
{
(action, index) in
let alert = FCAlertView()
alert.makeAlertTypeCaution()
alert.cornerRadius = 10
alert.delegate = self
alert.animateAlertInFromBottom = true
alert.animateAlertOutToTop = true
alert.bounceAnimations = true
alert.blurBackground = true
alert.dismissOnOutsideTouch = true
alert.showAlert(inView: self,
withTitle: "Title you want ",
withSubtitle: "Subtitle Comes here",
withCustomImage: nil,
withDoneButtonTitle:"OK" ,
andButtons:["Cancel"])
}
let edit = UITableViewRowAction(style: .default, title: "Edit")
{
(action, index) in
self.view.makeToast("Editing Coming soon...")
}
del.backgroundColor = AppColor.myNewRedColor
edit.backgroundColor = .lightGray
return [edit,del]
}
Swift 4.0
Add Delegate & DataSource
tableView.delegate = self
tableView.dataSource = self
Add DataSource func "canEditRowAt indexPath"
//MARK: - UITableViewDataSource
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
Add Delegate func "editActionsForRowAt indexPath"
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
//Action edit
print("Action Edit...")
})
editAction.backgroundColor = UIColor.gray //Set button color
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
//Action delete
print("Action Delete...")
})
return [deleteAction, editAction]
}
I hope this helps.
As par your Requirement i have . created Demo for you.
Here is the Output,
When you press Delete element will be removed from Array and when you press Add Button element will be added to new Array.
Here is the link of Demo,
Tableview Demo with Swipable Add and Delete
Step 1:- Connect your Tableview datasource and delegate in Storyboard.
Step 2:- Write DataSource Methods of TableView.
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Preloaded Data"
} else {
return "Added Data to New Array"
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return arrPrelodedData.count
} else {
return arrAddNewData.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwipeToDelete", for: indexPath) as? SwipeToDelete else {return UITableViewCell()}
if indexPath.section == 0{
cell.lblCellContent.text = arrPrelodedData[indexPath.row] }
else {
cell.lblCellContent.text = arrAddNewData[indexPath.row]
}
return cell
}
//With this we can edit UITableview ex. Swipe to Delete
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0 {
return true } else {
return false
}
}
//Select tableview Editing Style (insert and Delete)-> if custom icon than set None
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.none
}
//Delete Action 1) Create delete Action 2) Remove data with Indexpath 3) fetch data from coredata 4) delete tableview row 4) set delete button background color 5) return deleteAction in arry wether it is single
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//Destructive Because we want to delete(destroy) the data from tableview
let deleteAction = UITableViewRowAction(style: .destructive, title: "DELETE") { (rowAction, indexpath) in
self.arrPrelodedData.remove(at: indexPath.row)
tableView.deleteRows(at: [indexpath], with: .automatic)
}
let addAction = UITableViewRowAction(style: .normal, title: "ADD 1") { (rowAction, indexpath) in
self.arrAddNewData.append(self.arrPrelodedData[indexPath.row])
tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
// tableView.reloadRows(at: [indexPath], with: .automatic)
}
deleteAction.backgroundColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
addAction.backgroundColor = #colorLiteral(red: 0.9176470588, green: 0.662745098, blue: 0.2666666667, alpha: 1)
return [deleteAction,addAction]
}
}
I hope this answer will helpful for you.
In my project, there is a requirement to call editActionsForRowAt of a UITableView on a button action. So that on clicking that button, tableview swipes left.
My editActionsForRowAt code:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .normal, title: "Edit".localized) {[weak self] (rowAction, indexPath) in
// Perform edit action here
}
let deleteAction = UITableViewRowAction(style: .normal, title: "Delete".localized) {[weak self] (rowAction, indexPath) in
// Perform delete action here
}
return [deleteAction,editAction]
}
I do not know whether it is possible or not? I have searched a lot but did not find any solution. Please suggest is it possible or not? If yes, then how to achieve this?
class YourViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CustomCellDelegate {
#IBOutlet weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "identifier") as? CustomCell else {
return UITableViewCell()
}
cell.indexPath = indexPath
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return nil
}
func delete(for cell: CustomCell) {
let indexPath = cell.indexPath
print("doing action for cell at: \(indexPath!.row)")
// your implementation for action
// maybe delete a cell or whatever?
cell.hideDeleteActions()
}
}
protocol CustomCellDelegate: class {
func delete(for cell: CustomCell)
}
class CustomCell: UITableViewCell {
weak var delegate: CustomCellDelegate?
var indexPath: IndexPath!
#IBOutlet weak var buttonAction: UIButton?
#IBOutlet weak var constBtnDeleteAction: NSLayoutConstraint?
override func awakeFromNib() {
self.constBtnDeleteAction?.constant = 0
}
override func touchesEnded(_ touches: Set<UITouch>,
with event: UIEvent?) {
guard let point = touches.first?.location(in: self) else {
return
}
if self.point(inside: point, with: event) {
self.showDeleteActions()
}
}
func showDeleteActions() {
self.constBtnDeleteAction?.constant = 100
// Set it according to the button width
UIView.animate(withDuration: 0.3) {
self.layoutIfNeeded()
}
}
func hideDeleteActions() {
self.constBtnDeleteAction?.constant = 0
UIView.animate(withDuration: 0.3) {
self.layoutIfNeeded()
}
}
#IBAction func cellButtonAction() {
delegate?.delete(for: self)
}
}
You need to do more with storyboard like setting constraints of button which will be at the rightmost in the cell and join the outlets.
I think it is possible by call your tableview's delegate method as below
#IBAction func editingstylecalled(_ sender:UIButton)
{
let tag = sender.tag
self.tableView(self.tableview, commit: .delete, forRowAt: IndexPath.init(row: tag, section: 0))
}
Please set your tableview in above code and check.
I'm getting an error with my code that says...
"Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
with identifier ItemCell - must register a nib or a class for the
identifier or connect a prototype cell in a storyboard'?"
I've set the cell to ItemCell and I've run Product > Clean. It still can't find it. Can anyone see what I've done wrong? I've included a screen shot of my code and my storyboard.
import UIKit
class ItemsViewController: UITableViewController {
var itemStore: ItemStore!
#IBAction func addNewItem(_ sender: UIButton) {
let newItem = itemStore.createItem()
if let index = itemStore.allItems.index(of: newItem) {
let indexPath = IndexPath(row: index, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
#IBAction func toggleEditingMode(_ sender: UIButton) {
if isEditing {
sender.setTitle("Edit", for: .normal)
setEditing(false, animated: true)
} else {
sender.setTitle("Done", for: .normal)
setEditing(true, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let insets = UIEdgeInsetsMake(statusBarHeight, 0, 0, 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
tableView.rowHeight = 65
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemStore.allItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
let item = itemStore.allItems[indexPath.row]
cell.nameLabel.text = item.name
cell.serialNumberLabel.text = item.serialNumber
cell.valueLabel.text = "$\(item.valueInDollars)"
return cell
}
override func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let item = itemStore.allItems[indexPath.row]
let title = "Delete \(item.name)"
let message = "You sure ya wanna delete this?"
let ac = UIAlertController(title: title,
message: message,
preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
ac.addAction(cancelAction)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action) -> Void in
self.itemStore.removeItem(item)
self.tableView.deleteRows(at: [indexPath], with: .automatic)
})
ac.addAction(deleteAction)
present(ac, animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView,
moveRowAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath) {
itemStore.moveItem(from: sourceIndexPath.row, to: destinationIndexPath.row)
}
This is my ItemCell
import UIKit
class ItemCell: UITableViewCell {
#IBOutlet var nameLabel: UILabel!
#IBOutlet var serialNumberLabel: UILabel!
#IBOutlet var valueLabel: UILabel!
}
And my ItemStore
import UIKit
class ItemStore {
var allItems = [Item] ()
#discardableResult func createItem() -> Item {
let newItem = Item(random: true)
allItems.append(newItem)
return newItem
}
func removeItem(_ item: Item) {
if let index = allItems.index(of: item) {
allItems.remove(at: index)
}
}
func moveItem(from fromIndex: Int, to toIndex: Int) {
if fromIndex == toIndex {
return
}
let movedItem = allItems[fromIndex]
allItems.remove(at: fromIndex)
allItems.insert(movedItem, at: toIndex)
}
}
You have to check your custom class name in storyboard as ItemCell.swift as your class name.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:ItemCell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as! ItemCell
let item = itemStore.allItems[indexPath.row]
cell.nameLabel.text = item.name
cell.serialNumberLabel.text = item.serialNumber
cell.valueLabel.text = "$\(item.valueInDollars)"
return cell
}
Check if you have set the correct custom class for the cell (ItemCell in this case) in Identity Inspector.
UITableViewCell sub class:
class MenuDrawerTableViewCell: UITableViewCell {
#IBOutlet weak var Label3: UILabel!
#IBOutlet weak var Image30: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}}
I have that class, now I got my viewController which has a table.
class OpenMenu: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableV: UITableView!
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
var selected = 0
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("prepare")
var DestVC = segue.destination as! CheckinController
var indexPath: NSIndexPath = self.tableV.indexPathForSelectedRow! as NSIndexPath
let menuItem = menuList[indexPath.row]
DestVC.varView = menuItem.index
}
let newSwiftColor = UIColor(red: CGFloat(255), green: CGFloat(0), blue: CGFloat(238), alpha: CGFloat(1))
var menuList = [Menu]()
func loadMenu() {
let photo1 = UIImage(named: "checkin")!
let menu1 = Menu(name: "Check In", photo: photo1, index: 20)!
let photo2 = UIImage(named: "checkin")!
let menu2 = Menu(name: "Add Store", photo: photo2, index: 10)!
menuList += [menu1, menu2]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuList.count // your number of cell here
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "MenuDrawerTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath as IndexPath) as! MenuDrawerTableViewCell
let menuItem = menuList[indexPath.row]
cell.Image30.image = menuItem.photo
cell.Label3.text = menuItem.name
cell.Label3.numberOfLines = 1;
if(0 == selected)
{
selected = 1
self.tableV.selectRow(at: indexPath, animated: true, scrollPosition: UITableViewScrollPosition.none)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
// cell selected code here
print("cell selected")
print(indexPath)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuDrawerTableViewCell", for: indexPath as IndexPath) as UITableViewCell
return cell
}
#IBOutlet weak var Open: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
loadMenu()
self.tableV.delegate = self
self.tableV.dataSource = self
let size:CGFloat = 35.0 // 35.0 chosen arbitrarily
let preferences = UserDefaults.standard
let name1 = ""+preferences.string(forKey: "name")!
label2.text = name1
label1.text = String(name1[name1.startIndex])
label2.textColor = UIColor.white
label1.textColor = UIColor.white
label1.textAlignment = NSTextAlignment.center
label1.font = UIFont.systemFont(ofSize: 17)
label1.bounds = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: size, height: size))
label1.layer.cornerRadius = size / 2
label1.layer.borderWidth = 3.0
label1.layer.backgroundColor = newSwiftColor.cgColor
label1.layer.borderColor = UIColor.black.cgColor
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
What I want, is detect the click on a tableview. But I am not able to detect anything .I supposedly should get cell selected printed, but i am getting nothing.Why the click function not getting called?
I think you need to selection of tableview as below :
You can check your code you have to implemented two time methods(cellForRowAtIndexPath and cellForRowAt)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
First make sure that you have connected tableview and connected delegate and datasource also.
Please remove these lines of code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuDrawerTableViewCell", for: indexPath as IndexPath) as UITableViewCell
return cell
}
As already you implemented this method.
Hope this will fix your problem.
I had this problem and noticed that somehow "isEditing" was set to "true" for the tableView in my viewDidLoad code... removing that line of code fixed it.