I am creating an app where in the menus are listed inside TableViewCell. The menus are already inside the cell but unfortunately, when I clicked one of the menus, It is not executing the action that the menu should do. For example, i tapped the logout label it does not executing showlogoutDialog. I already used breakpoints but it seems the data inside the table are just plain text. Image below is the sample output of the table. Hope you can give some solution regarding this issue. Thank you.
DoctorMenuTableCell.swift
class DoctorMenuTableCellTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: 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
}
MoreOptionViewController.swift
private let menuIdentifier = "MenuCell"
class MoreOptionViewController: UIViewController {
#IBOutlet weak var doctorMenuTableView: UITableView!
}
override func viewDidLoad() {
super.viewDidLoad()
self.doctorMenuTableView.dataSource = self
self.doctorMenuTableView.delegate = self
}
//MARK: Function
func showLogoutDialog() {
//create alert
let alert = UIAlertController(title: "Confirmation", message: "Are you sure you want to logout?", preferredStyle: .alert)
//add the actions (button)
alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert) in
self.logout()
}))
self.present(alert, animated: true, completion: nil)
}
func logout() {
NotificationCenter.default.post(name: Notification.Name(deleteUserDataNotificationName), object: nil)
}
}
extension MoreOptionViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return Menu.More.items.count
default: return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: menuIdentifier, for: indexPath) as! DoctorMenuTableCell
cell.titleLabel.text = Menu.More.items[row].value
if row == 1{
cell.titleLabel.textColor = UIColor.red
cell.accessoryType = .none
}
return cell
default:
return UITableViewCell()
}
}
func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0: break
case 1:
switch indexPath.row {
case 0:
let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
case 1: showLogoutDialog()
default: break
}
default: break
}
}
Check your Did Select Method, your cells are under Section 0 and Did Select work for section 1.
Also check isUserInteractionEnabled for both TableView as well as Cell and add breakpoint on didSelectRowAt and check which switch case is working.
Code:
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return Menu.More.items.count
default: return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: menuIdentifier, for: indexPath) as! DoctorMenuTableCell
cell.titleLabel.text = Menu.More.items[row].value
if indexPath.row == 1{
cell.titleLabel.textColor = UIColor.red
cell.accessoryType = .none
}
return cell
default:
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 1: break
case 0:
switch indexPath.row {
case 0:
let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
break
case 1: showLogoutDialog()
break
default: break
}
break
default: break
}
}
Look how many sections you have. You have just one, but inside didSelectRowAt you're showing alerts just if section index is 1 which in you case index never is.
You just need to check if row is 0 or 1
func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
case 1:
showLogoutDialog()
default:
return
}
}
So, if you have only one section, you can also update data source methods. Also you should handle cases that cell isn't in IndexPath with row index 1 since cells are dequeued
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Menu.More.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: menuIdentifier, for: indexPath) as! DoctorMenuTableCell
let row = indexPath.row
cell.titleLabel.text = Menu.More.items[row].value
cell.titleLabel.textColor = .black
cell.accessoryType = .detailButton
if row == 1
cell.titleLabel.textColor = .red
cell.accessoryType = .none
}
return cell
}
First Create Extension if UIViewController as Below,
Create a swift File Named Extension.swift or whatever you want,
extension UIViewController
{
func showLogoutDialog() {
//create alert
let alert = UIAlertController(title: "Confirmation", message: "Are you sure you want to logout?", preferredStyle: .alert)
//add the actions (button)
alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert) in
self.logout()
}))
self.present(alert, animated: true, completion: nil)
}
func logout() {
print("helllllo")
NotificationCenter.default.post(name: Notification.Name(deleteUserDataNotificationName), object: nil)
}
}
Now call showLogoutDialog() on cellForRowAt,
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 1: break
case 0:
switch indexPath.row {
case 0:
let alertController = UIAlertController(title: "Info", message: "your data", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
break
case 1: showLogoutDialog()
break
default: break
}
break
default: break
}
Related
I have a basic quiz where the uitableview presents four cells. Three cells have wrong answers, and one has a correct answer. I already have included alerts, so this tells the user where he/she has been incorrect and where they are correct.
I have tried to also include a haptic function, however when I run the app on an iPhone 7, the haptic function does not work despite no errors from x code.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentQuestion?.answers.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = currentQuestion?.answers[indexPath.row].text
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let question = currentQuestion else {
return
}
let answer = question.answers[indexPath.row]
if checkAnswer(answer: answer, question: question) {
// correct
if let index = gameModels.firstIndex(where: { $0.text == question.text }) {
if index < (gameModels.count - 1){
func correct (_sender: UITableViewCell){
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
}
// next question
let nextQuestion = gameModels[index + 1]
print("\(nextQuestion.text)")
currentQuestion = nil
configureUI(question: nextQuestion)
}
else{
// end of game
let alert = UIAlertController(title: "Done", message: "You beat the game", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
present(alert, animated: true)
}
}
}
else {
//wrong
let alert = UIAlertController(title: "Wrong", message: "Try again", preferredStyle: .alert)
func wrongTap (_ sender: UITableViewCell){
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
}
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
present(alert, animated: true)
}
Try to use impactAccurred instead:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.prepare()
generator.impactOccurred()
Essentially I have a tableView that is separated by sections.
The tableView allows for multiple row selections and displays an accessory .checkmark on all selected rows.
If the user begins to select rows under one section and try to select a different row under a different I would like for an alert message to appear and the selection not be made.
The following is the code so far:
import UIKit
class TableViewController: UITableViewController {
var Name = UserDefaults.standard.string(forKey: "name")!
var sections = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
navigationController?.navigationBar.prefersLargeTitles = true
fetchJSON()
self.tableView.allowsMultipleSelection = true
}
}
Implement UITableViewDelegate method tableView(_:willSelectRowAt:).
Use map(_:) to get the sections from indexPathsForSelectedRows.
Check if the indexPath's section in tableView(_:willSelectRowAt:) is contained in the previously obtained sections array using contains(_:)
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let sections = tableView.indexPathsForSelectedRows?.map({ $0.section }) {
if !sections.contains(indexPath.section) {
//Show Alert here....
let alert = UIAlertController(title: "Alert..!!", message: "You're selection row from Section:\(indexPath.section)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
return nil
}
}
return indexPath
}
tableView(_:willSelectRowAt:) return value : An index-path object
that confirms or alters the selected row. Return an NSIndexPath object
other than indexPath if you want another cell to be selected. Return
nil if you don't want the row selected.
Check out tableView(_:willSelectRowAt:). You can return nil from this delegate method to prevent a row from being selected.
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let
indexPathsForSelectedRows = tableView.indexPathsForSelectedRows, indexPathsForSelectedRows.count > 0,
indexPath.section != indexPathsForSelectedRows[0].section
{
// If there is at least one row already selected
// And the section of that row is different than the section of the row about to be selected
// Don't allow the selection
let alertController = UIAlertController(title: "Whoops!", message: "Don't do that!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
return nil
}
// There's either nothing selected yet or the section of this row is the same as those already selected
return indexPath
}
I think, you need to create an extra logic for it, per example.
You can put in one array all the indexPath you selected, and compare always the first item(indexPath) with each item you will go to add, the indexPath contains the property Section so just need to compare if the section are equals or not, if it isn't, you show de alert you want, after that you deselect the item manually.
var selectedItems = [IndexPath]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let firstIndexPath = selectedItems.first{
//If the section with the first element selected and the new selection are not equals, display your message
if indexPath.section != firstIndexPath.section{
let alert = UIAlertController(title: "Warning", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: {
a in
self.selectIndexPath(indexPath: indexPath, isSelected: false)
}))
//You can put it here if you prefer not wait for the closure for realize the deselection
//self.selectIndexPath(indexPath: indexPath, isSelected: false)
self.present(alert, animated: true, completion: nil)
return
}
self.selectIndexPath(indexPath: indexPath, isSelected: true)
}else{
self.selectIndexPath(indexPath: indexPath, isSelected: true)
}
}
func selectIndexPath(indexPath: IndexPath, isSelected: Bool){
tableView.cellForRow(at: indexPath)?.accessoryType = isSelected ? .checkmark : .none
if isSelected{
selectedItems.append(indexPath)
}else{
selectedItems.removeAll(where: {$0 == indexPath})
tableView.deselectRow(at: indexPath, animated: true)
}
let section = sections[indexPath.section]
let item = section.items[indexPath.row]
// for all selected rows assuming tableView.allowsMultipleSelection = true
}
From what I understand you can do the following:
Add a bool value on your section struct to check if you have any item selected
struct Section {
let name : String
var hasItemsSelected: Bool
let items : [Portfolios]
}
change your didSelectRowAt
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//when you select a row check if there is another row selected on another section by checking if the hasItemsSelected is true on all other sections
//1. create an array containing all section besides the current section
let allOtherSections = sections
.enumerated()
.filter { $0.offset != indexPath.section }
.map { $0.element }
//2. if allOtherSections does not have seledcted items
if allOtherSections.allSatisfy { $0.hasItemsSelected == false } {
self.sections[indexPath.section].hasItemsSelected = true
tableView.cellForRow(at: ind exPath)?.accessoryType = .checkmark
} else {
let numberOfSelectedRowsOnCurrentIndexPath = tableView.indexPathsForSelectedRows?.enumerated().filter { $0.offset != 1 }.count
if numberOfSelectedRowsOnCurrentIndexPath == 0 {
self.sections[indexPath.section].hasItemsSelected = false
}
tableView.deselectRow(at: indexPath, animated: true)
//show the alert here
let alertController = UIAlertController(title: "Title", message: "Your message", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
I hope I have helped you
How can I change the title of an UIAlertAction when I click the button ?
I want to click that button and from "Enable" to make it "Disable" for example.
I spent a lot of time trying to achieve this but I can't manage to do it.
Here is a small Demo with my issue: https://github.com/tygruletz/ChangeTitleOfAlertAction
Here is my code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.tableFooterView = UIView()
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
showOptions()
}
func showOptions(){
var enable = "Enable"
let disable = "Disable"
let applyOn = UIAlertAction(title: enable, style: .default, handler: { (action: UIAlertAction!) in
enable = disable
})
let actionSheet = configureActionSheet()
actionSheet.addAction(applyOn)
self.present(actionSheet, animated: true, completion: nil)
}
func configureActionSheet() -> UIAlertController {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheet.addAction(cancel)
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
actionSheet.popoverPresentationController?.sourceView = self.view
actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
actionSheet.popoverPresentationController?.permittedArrowDirections = []
}
return actionSheet
}
}
And here is a capture of screen:
Thank you if you try to help me !
Please follow below code:
Define property in your UIViewController
var selectedIndexPath:IndexPath!
Add argument in showOptions method
func showOptions(indexPath:IndexPath){
var status = "Enable"
if selectedIndexPath == indexPath{
status = "Disable"
}
let applyOn = UIAlertAction(title: status, style: .default, handler: { (action: UIAlertAction!) in
if self.selectedIndexPath == indexPath{
self.selectedIndexPath = nil
}else{
self.selectedIndexPath = indexPath
}
})
let actionSheet = configureActionSheet()
actionSheet.addAction(applyOn)
self.present(actionSheet, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
showOptions(indexPath: indexPath)
}
Note:
If you are going with this approach, Then you will never faced cell usability issue.
I have a subclass of UITableView in my iOS app (Swift 4, XCode 9). This table has one row and I want it to display an alert when it's clicked, get some input from the user, and then update a label (lblUserFromPrefs) in the table when the user clicks "OK" in the alert. Currently everything works fine except the label doesn't get updated. Here is the relevant code from my UITableView subclass:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Clicked section: \(indexPath.section) row: \(indexPath.row)")
let alert = UIAlertController(title: "Username", message: "what is your name", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = ""
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert!.textFields![0]
if let text = textField.text {
print("Text field: \(text)")
DispatchQueue.main.async {
self.lblUserFromPrefs.text = text
print("label updated")
}
}
}))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
What happens when I run this is the label's text doesn't change when the alert closes but does change immediately when the table row is clicked again. I don't know why it waits until the row is clicked again to update the text. All the print statements print when I expect (including printing "label updated" immediately when the alert's OK button is pressed) and they print the right things. I know that when you're trying to update the UI from a closure in a background thread you have to use DispatchQueue.main.async {} but I'm not sure why it's not updating even though I am using the main thread. I have tried using DispatchQueue.main.async(execute: {}) and putting self.lblUserFromPrefs.setNeedsDisplay() directly after self.lblUserFromPrefs.text = "text". Any ideas what I'm doing wrong? Thanks!!
Add the [weak self] to the dispatch like this:
DispatchQueue.main.async { [weak self] in
}
Try something like this:
let alertController = UIAlertController.init(title: "Enter some text", message: nil, preferredStyle: .alert)
alertController.addTextField { (textField) in
// Text field configuration
textField.placeholder = "Enter..."
textField.text = ""
}
alertController.addAction(UIAlertAction.init(title: "Ok", style: .default, handler: { (action) in
if (alertController.textFields?.first?.hasText)! {
if let text = alertController.textFields?.first?.text {
self.label.text = text // Update the value
}
} else {
self.label.text = "" // Default value
}
}))
self.present(alertController, animated: true, completion: nil) // Present alert controller
Here is the sample code for the behavior you want to achieve. Just include your alert controller code in didSelect and you should be good to go!
import UIKit
import PlaygroundSupport
class MyViewController : UITableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell()
}
cell!.textLabel?.text = "Hello World!"
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.textLabel?.text = "Hello Universe!"
}
}
I have a UITableView and when I add data, it will only allow me to add one row in the UITableview even though I return goals.count for the amount of rows.
This is what I have.
#IBAction func myAddGoal(sender: AnyObject) {
let ac = UIAlertController(title: "Enter a Goal", message: "It can be anything you want!", preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
let submit = UIAlertAction(title: "Submit", style: .Default) { [unowned self, ac] (action: UIAlertAction!) in
let goal = ac.textFields![0] as UITextField
self.submitGoal(goal.text)
}
ac.addAction(submit)
ac.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
func submitGoal(goal: String){
if goal == "" {
println("textfield is empty")
} else {
goals.insert(goal, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
println(goals)
}
}
I am able to add only ONE goal and it will animate into the UITableView. If I want to add another goal, it will not let me. The app crashes when I hit submit for a second goal entry.
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return goals.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = goals[indexPath.row]
cell.textLabel!.text = object
mySwitch.on = false
mySwitch.tag = indexPath.row as Int
mySwitch.addTarget(self, action: "UISwitchUpdated", forControlEvents: UIControlEvents.TouchUpInside)
cell.selectionStyle = .None
cell.accessoryView = mySwitch
return cell
}