Call function from UITableViewCell from in ViewController Swift - ios

I need to call function deleteButtonShowHide, which is in TeamsCell, from TeamsVC, when plusBtnTapped. I am trying to figure it out with protocol TeamsVCDelegate, but it doesn't work( It works vice versa for me. But I do not know how to implement something like cell.teamsCellDelegate = self
TeamsCell
import UIKit
protocol TeamsCellDelegate {
func deleteCell()
}
class TeamsCell: UITableViewCell {
#IBOutlet weak var teamNameLbl: UILabel!
#IBOutlet weak var deleteButton: UIButton!
var teamsCellDelegate: TeamsCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func updateCell(team: team) {
teamNameLbl.text = team.name
}
#IBAction func deleteButtonTapped(_ sender: Any) {
debugPrint("delet tapped")
//deleteButtonShowHide()
findAndDeleteTeam()
teamsCellDelegate?.deleteCell()
}
func findAndDeleteTeam() {
for i in 0...teams.count - 1 {
if teams[i].name == teamNameLbl.text {
teams.remove(at: i)
break
}
}
}
func deleteButtonShowHide(){
if teams.count < 3 {deleteButton.isHidden = true}
if teams.count > 2 {deleteButton.isHidden = false}
}
}
extension TeamsCell: TeamsVCDelegate {
func deleteButtonSH() {
debugPrint("XXX")
deleteButtonShowHide()
}
}
TeamsVC
import UIKit
protocol TeamsVCDelegate {
func deleteButtonSH()
}
class TeamsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var plusBtn: UIButton!
#IBOutlet weak var teamsTable: UITableView!
var teamsVCDelegate: TeamsVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
teamsTable.delegate = self
teamsTable.dataSource = self
teamsTable.rowHeight = 55
teamsTable.isScrollEnabled = false
teamsTable.backgroundColor = nil
teamsTable.separatorStyle = .none
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return teams.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
#IBAction func plusBtnTapped(_ sender: Any) {
plusBtnHide()
addTeam()
teamsTable.reloadData()
teamsVCDelegate?.deleteButtonSH()
print(teams)
}
func plusBtnShow() {
if teams.count < 5 {plusBtn.isHidden = false}
}
func plusBtnHide() {
if teams.count == 4 { plusBtn.isHidden = true}
}
}
extension TeamsVC: TeamsCellDelegate {
func deleteCell() {
self.teamsTable.reloadData()
self.plusBtnShow()
}
}

You could call deleteButtonShowHide function when you are loading/setting up a cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.deleteButtonShowHide() // <-- HERE
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
By the way, your cell should not contain such logic in the first place. It should depend on some data model object which then should be used to setup your cell correctly (show/hide UI elements, etc.).

You could simplify by setting the button show/hide when computing the number of row.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if teams.count < 5 {plusBtn.isHidden = false}
if teams.count == 4 { plusBtn.isHidden = true}
return teams.count
}
And set the delebutton visibility when creating the cell :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
// cell.teamsCellDelegate = self
cell.deleteButton.isHidden = (teams.count < 3)
return cell
}
return UITableViewCell()
}
So no need for delegate and cell does not have to know about the model (teams)

Related

UISearchBar is not searching when entering text

I have a Table View that is working fine. However, when I try to implement a UISearchBar and display filtered data, nothing gets filtered. This is my View Controller:
import UIKit
class MealPlanViewController: UIViewController, UISearchBarDelegate {
private var model = MealPlanModel()
private var mealPlan = [MealPlan]()
var filteredData: [MealPlan]!
#IBOutlet weak var topBarStackView: UIStackView!
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
model.delegate = self
searchBar.delegate = self
filteredData = mealPlan
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = []
if searchText == "" {
filteredData = mealPlan
}
else {
for item in mealPlan {
if ((item.title?.lowercased().contains(searchText.lowercased())) != nil) {
filteredData.append(item)
}
}
}
self.tableView.reloadData()
}
}
extension MealPlanViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MealPlanCell", for: indexPath) as! MealPlanCell
let filteredMealPlaninTable = filteredData[indexPath.row]
cell.displayMealPlan(filteredMealPlaninTable)
return cell
}
}
extension MealPlanViewController: MealPlanProtocol {
func mealPlansRetrieved(mealPlans: [MealPlan]) {
self.filteredData = mealPlans
tableView.reloadData()
}
}
A couple of notes:
When I run a print(self.filteredData) in my `func mealPlansRetrieved', the console returns all of my data as if it wasn't filtered, but
As soon as I start typing in the search bar, the table view doesn't return any cells, which seems contradictory to the above
For reference, this is the code before filtering that did work:
extension MealPlanViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealPlan.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MealPlanCell", for: indexPath) as! MealPlanCell
let mealPlanInTable = mealPlan[indexPath.row]
cell.displayMealPlan(mealPlanInTable)
return cell
}
}
extension MealPlanViewController: MealPlanProtocol {
func mealPlansRetrieved(mealPlans: [MealPlan]) {
self.mealPlan = mealPlans
tableView.reloadData()
}
}
Any help/guidance is much appreciated!
Contains returns boolean so this will never fail: item.title?.lowercased().contains(searchText.lowercased())) != nil
To make check work you can simply remove "!= nil".
Im not sure from where you are calling mealPlansRetrieved, but you might want to keep the line "self.mealPlan = mealPlans" instead of "self.filteredData = mealPlans".

DidSelectRowAt won't return desired item

I have dynamic table which displays a number of MKMapItems - these items are being displayed by cellForRowAt. But somehow if I click on the cell didSelectRow won't return the map item if I want to print it:
class SearchResultTableViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var visualEffectView: UIVisualEffectView!
private enum SegueID: String {
case showDetail
case showAll
}
private enum CellReuseID: String {
case resultCell
}
private var places: [MKMapItem]? {
didSet {
tableView.reloadData()
}
}
private var suggestionController: SuggestionsTableTableViewController!
var searchController: UISearchController!
private var localSearch: MKLocalSearch? {
willSet {
places = nil
localSearch?.cancel()
}
}
private var boundingRegion: MKCoordinateRegion?
override func awakeFromNib() {
super.awakeFromNib()
...
}
override func viewDidLoad() {
super.viewDidLoad()
...
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if #available(iOS 10, *) {
visualEffectView.layer.cornerRadius = 9.0
visualEffectView.clipsToBounds = true
}
}
...
}
extension SearchResultTableViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseID.resultCell.rawValue, for: indexPath)
if let mapItem = places?[indexPath.row] {
cell.textLabel?.text = mapItem.name
cell.detailTextLabel?.text = mapItem.placemark.formattedAddress
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print(indexPath)
...
guard let mapItem = places?[indexPath.row] else { return }
print(mapItem.name)
...
if tableView == suggestionController.tableView, let suggestion = suggestionController.completerResults?[indexPath.row] {
searchController.isActive = false
searchController.searchBar.text = suggestion.title
search(for: suggestion)
}
}
}
guard let mapItem = places?[indexPath.row] else { return }
- are you sure this guard statement isn't returning?
also, I'm not seeing where you're setting the VC as the tableView delegate/datasource.

UITableViewCell multiple select circle (Edit Control) coming randomly

I created a ViewController with a UITableView as a subView.
import UIKit
class ViewController: UIViewController {
private var tableDataSource = [
"Lorem Ipsum is simply du.",
"It is a long established .",
"Lorem Ipsum come",
"All the Lorem .",
"The standard ch.",
"The generated.",
"Various versions."
]
private var isReorderingEnabled = false
private var isDeleteEnabled = false
#IBOutlet private var reorderCellsBarButton: UIBarButtonItem!
#IBOutlet private var selectCellsBarButton: UIBarButtonItem! {
didSet {
selectCellsBarButton.tag = ButtonTags.Select
}
}
#IBOutlet private var deleteCellsBarButton: UIBarButtonItem! {
didSet {
deleteCellsBarButton.tag = ButtonTags.Delete
}
}
#IBOutlet weak private var tableView: UITableView! {
didSet {
tableView.dataSource = self
tableView.delegate = self
tableView.allowsMultipleSelectionDuringEditing = false
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
}
}
}
extension ViewController {
private struct ButtonTags {
static let Delete = 2
static let Select = 1
}
private struct LocalizedStrings {
static let EnableReorderingText = "Reorder"
static let DisableReorderingText = "Done"
static let EnableSelectionText = "Select"
static let ConfirmDeletionText = "Delete"
static let DisableDeletionText = "Cancel"
}
}
extension ViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setDeleteBarButton(hidden: true, animated: false)
}
}
// IBActions
extension ViewController {
#IBAction private func reorderCells(_ sender: UIBarButtonItem) {
isReorderingEnabled = !tableView.isEditing
setSelectBarButton(hidden: isReorderingEnabled)
sender.title = isReorderingEnabled ? LocalizedStrings.DisableReorderingText : LocalizedStrings.EnableReorderingText
tableView.setEditing(isReorderingEnabled, animated: true)
tableView.reloadData()
}
#IBAction private func deleteCells(_ sender: UIBarButtonItem) {
isDeleteEnabled = !tableView.isEditing
setDeleteBarButton(hidden: !isDeleteEnabled)
selectCellsBarButton.title = isDeleteEnabled ? LocalizedStrings.DisableDeletionText : LocalizedStrings.EnableSelectionText
if sender.tag == ButtonTags.Delete {
deleteSelectedRows()
}
tableView.allowsMultipleSelectionDuringEditing = isDeleteEnabled
tableView.setEditing(isDeleteEnabled, animated: true)
tableView.reloadData()
}
}
// Custom Helper methods
extension ViewController {
private func setDeleteBarButton(hidden: Bool, animated: Bool = true) {
navigationItem.setRightBarButtonItems([(hidden ? reorderCellsBarButton : deleteCellsBarButton)], animated: animated)
}
private func setSelectBarButton(hidden: Bool, animated: Bool = true) {
self.navigationItem.setLeftBarButton((hidden ? nil : selectCellsBarButton), animated: animated)
}
private func deleteSelectedRows() {
guard let selectedRows = tableView.indexPathsForSelectedRows else { return }
let indexes = selectedRows.map { $0.row }
tableDataSource.remove(indexes: indexes)
tableView.deleteRows(at: selectedRows, with: .fade)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier, for: indexPath) as! CustomTableViewCell
customCell.setup(content: tableDataSource[indexPath.row], for : indexPath.row)
return customCell
}
}
// pragma - To Select/Edit/Move TableView Cells
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
tableDataSource.move(from: sourceIndexPath.row, to: destinationIndexPath.row)
let reloadingIndexPaths = IndexPath.createForNumbers(from: sourceIndexPath.row, to: destinationIndexPath.row)
DispatchQueue.main.async {
tableView.reloadRows(at: reloadingIndexPaths, with: .none)
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableDataSource.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .none)
}
}
}
// pragma - Settings for Edit/Move TableViewCell
extension ViewController {
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
print("Edit- \(tableView.isEditing)")
return tableView.isEditing
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
print("Move- \(isReorderingEnabled)")
return isReorderingEnabled
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
print("Style- None")
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
print("indent- \(isDeleteEnabled)")
return isDeleteEnabled
}
}
In this, I have made three bar buttons,one for Reordering , and other two for Deletion and Cancellation.
So, for delete I have provided ability to select multiple rows.
But the problem is, when Reordering selected, the checkbox is still appearing(Not clickable though). And sometimes when Deletion selected, checkbox doesn't appear.
Cannot understand the absurd behaviour. Is this a bug of XCode ? Please help.
Added Content:
CustomTableViewCell class :
import UIKit
class CustomTableViewCell: UITableViewCell {
static let identifier = "customCellIdentifier"
#IBOutlet weak private var titleLabel: UILabel!
#IBOutlet weak private var backgroundImageView: UIImageView!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
let selectionView = UIView()
selectionView.backgroundColor = UIColor.clear
selectedBackgroundView = selectionView
}
}
extension CustomTableViewCell {
func setup(content: String, for rowNumber: Int) {
titleLabel.text = content
let backgroundImageName = rowNumber % 2 == 0 ? ImageAssetNames.BlueMatte : ImageAssetNames.GreenThreads
backgroundView = UIImageView(image: UIImage(named: backgroundImageName))
}
}

How to make textfield functional inside a tableview on swift

I'm trying to create a tableview where each cell has multiple textfields.
I was able to create a simple list with a textfield but when I press the textfield nothing happens. The keyboard does not popup and feels like the event is being captured by some other view.
I made sure that user interaction is set to enable.
I've tried to push the view to front like you can see in the comment.
What am I missing?
My table is called MainTable and
my InputviewCell is just a normal cell (xib) with a textfield named txtFieldTemp
import Foundation
import UIKit
class PrioritiesGridViewController: UIViewController,UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate
{
#IBOutlet var mainTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
mainTable.delegate = self
mainTable.dataSource = self
//mainTable.allowsSelection = false
}
let data = AuxClass()
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 62
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.everything().count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("InputTextViewCell", owner: self, options: nil)?.first as! InputTextViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.txtFieldTemp.delegate = self
cell.txtFieldTemp.text = "test"
cell.txtFieldTemp.allowsEditingTextAttributes = true
//self.view.bringSubview(toFront: cell.txtFieldTemp)
return cell;
}
override var canBecomeFirstResponder: Bool { return true}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.isEditing = true
}
}
class AuxClass
{
var objectsArray = [Objects(
field1: "teste",
field2: 3),
Objects(
field1: "teste1",
field2: 4)
]
struct Objects {
var field1: String!
var field2: Int
}
func everything() -> [Objects]
{
return objectsArray
}
}
Try with cell.txtFieldTemp.becomeFirstResponder(). Looking at the apple documentation I think it will force it to be the first responder.

Why is my UITableView not showing?

I can't figure out why my TableView is not showing. Its probably something stupid but all of my MenuItemStruct's are complete and not null and my table view seems set up correctly to me. There are no errors, but my cellForRowAt method is not getting called. Please help?
class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var menuNavigationDelegate: MenuNavigationDelegate?, menuManagerDelegate: MenuManagerDelegate?
var conferenceId = "conferenceId-1"
var isDataLoading = false
#IBOutlet
var menuTableView: UITableView?
var menuItems = Array<MenuItemStruct>()
#IBAction
func closeMenuTapped() {
self.menuManagerDelegate?.closeMenu()
}
override func viewDidLoad() {
self.menuTableView?.register(UINib(nibName: "MenuTableViewCell", bundle: nil), forCellReuseIdentifier: "menuCell")
self.isDataLoading = true
MenuDataManager.getMenuInformation(conferenceId: self.conferenceId) {
menuItems, response, error in
self.menuItems = menuItems!
self.isDataLoading = false
DispatchQueue.main.async {
self.menuTableView?.reloadData()
}
}
self.menuTableView?.reloadData()
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MenuTableViewCell = menuTableView!.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as! MenuTableViewCell
if (!self.isDataLoading) {
cell.setUpCellWithData(menuItem: menuItems[indexPath.row])
}
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(!self.isDataLoading) {
return self.menuItems.count
}
return 0;
}
}
You need to set the delegate and datasource of your table view. You have included the UITableViewDataSource and UITableViewDelegate protocols, but have not assigned a delegate and datasource for your tableview in the code.
Try something like this in your viewDidLoad:
self.menuTableView.delegate = self
self.menuTableView.dataSource = self

Resources