Updating UILabel from UIAlertAction handler not working in Swift 4 - ios

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!"
}
}

Related

How to include a haptic function on a UI Table View Cell

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()

How to display an error message when selecting a row that is in a different section

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 to execute data inside TableViewCell as a button?

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
}

Formatting issue when attempting to insert new rows in a UITableView

I am trying to use an alertViewController to get text, add it to my array of strings, and then reload the tableView with the newly added cell. There seems to be an issue with the formatting after it is reloaded.
import UIKit
class TableViewController: UITableViewController, UINavigationControllerDelegate {
// store the tasks in an array of strings
var tasks = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Task List"
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addRow))
}
func addRow() {
let ac = UIAlertController(title: "Add a task to the list", message: nil, preferredStyle: .alert)
// add a text field
ac.addTextField {
(textField) -> Void in
textField.placeholder = ""
}
// add "cancel" and "ok" actions
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
let createNewRow = UIAlertAction(title: "OK", style: .default) { action -> Void in
let text = ac.textFields?.first?.text
self.tasks.append(text!)
self.loadView()
}
ac.addAction(createNewRow)
present(ac, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Task", for: indexPath)
cell.textLabel?.text = tasks[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tasks.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
Your issue was you call self.loadView() instead of self.tableView.reloadData() in the alert view controller's action:
let createNewRow = UIAlertAction(title: "OK", style: .default) { action -> Void in
let text = ac.textFields?.first?.text
self.tasks.append(text!)
self.tableView.reloadData() // self.loadView() is wrong.
}
ac.addAction(createNewRow)
From Apple's document: https://developer.apple.com/reference/uikit/uiviewcontroller/1621454-loadview
You should never call this method directly. The view controller calls
this method when its view property is requested but is currently nil.
This method loads or creates a view and assigns it to the view
property.

swift 3 CoreData strange debugger warning when using UIAlertController with text

Hi I'm building the coreData for swift 3. I'm Using the Master-Detail Template (only ad 1 more detail field for the prototype cell). I created a alertController and handle text input then save to coreData. Don't know why there is strange debugger warning.
here is my insert function
func insertNewObject(_ sender: Any) {
let context = self.fetchedResultsController.managedObjectContext
let alert = UIAlertController(title: "User", message: "Please enter username", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
if let textField = alert.textFields?.first {
let newEvent = Event(entity: NSEntityDescription.entity(forEntityName: "Event", in: context)!, insertInto: context)
newEvent.timestamp = Date()
newEvent.user = textField.text
// Save the context.
context.saveContext()
}
}
alert.addAction(action)
alert.addTextField { (textField) in
textField.placeholder = "Enter username"
}
self.present(alert, animated: true, completion: nil)
}
When I run. Everything work fine but have this warning.
I'm using prototype cell with Detail template. Any using auto cell sizing
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Anyone know what it is and how to avoid this? Thanks

Resources