In my app I have table view controller. When the user types on the last row of tableview the action sheet should appears to ask for sign out. Here is my code for this action:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
//..
case 1:
//..
case 2:
//..
case 3:
let logOutMenu = UIAlertController(title: nil, message: "Are you sure want to logout?", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let logOutAction = UIAlertAction(title: "Log out", style: .default, handler: { (UIAlertAction) in
print("sign out")
})
logOutMenu.addAction(cancelAction)
logOutMenu.addAction(logOutAction)
self.present(logOutMenu, animated: true, completion: nil)
default: break
}
}
Everything works fine, however there is strange behaviour of action sheet. It takes approximately 10 seconds (or even more) to show action sheet. The same behaviour I have noticed on real device as well. What I'm doing wrong?
You have to call deselect row at index path without animation otherwise there two animations at the same time which confuses and gets longer time
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
//..
case 1:
//..
case 2:
//..
case 3:
let logOutMenu = UIAlertController(title: nil, message: "Are you sure want to logout?", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let logOutAction = UIAlertAction(title: "Log out", style: .default, handler: { (UIAlertAction) in
print("sign out")
})
logOutMenu.addAction(cancelAction)
logOutMenu.addAction(logOutAction)
self.present(logOutMenu, animated: true, completion: nil)
// Deselect your row it will fix it
tableView.deselectRow(at: indexPath, animated: false)
default: break
}
}
Related
I can't use the method present().
The error is:
Value of type 'ProductByBrandCollectiionView' has no member 'present'
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let alert = UIAlertController(title: "Alert", message: "You select\(NameArray[indexPath.row])", preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
print("You select \(NameArray[indexPath.row])")
self.present(alert, animated: true, completion: nil)
}
Because the ProductByBrandCollectiionView doesnt have present method.
Value of type 'ProductByBrandCollectiionView' has no member 'present'
You need to use an instance of UIViewController to show the alert
You can try this code for your alert in your didSelectItemAt for your collection view
func collectionView(_ collectionView: UICollectionView, didSelectItemAt
indexPath: IndexPath) {
let alert = UIAlertController(title: "Alert", message: "You select\(NameArray[indexPath.row])", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Ok", style: .default) { (alert: UIAlertAction!) -> Void in
}
alert.addAction(okayAction)
self.present(alert, animated: true, completion:nil)
}
Just make sure that your NameArray is correct :)
Maybe ProductByBrandCollectiionView is just a view, not a viewcontroller, so you cannot present a viewcontroller.
Some solutions that you can try :
First, create a delegate, so that you can pass the action didSelectItemAt from ProductByBrandCollectiionView to your current viewcontroller.
Or you can create a closure, working the same way with delegate above
In OrderFormViewController I've a tableView and the tableViewCell I've a cameraButton that will show an alert when tapped.
Now when OrderFormViewController is presented (not pushed) it loads tableView and it's cell (Row count is 1 hard coded).
I've the following code under the IBAction of cameraButton:
#IBAction func cameraButtonPressed(_ sender: Any) {
//DispatchQueue.main.async {
let alert = UIAlertController(title: "Choose Image From", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
self.imagePicker.allowsEditing = true
UIApplication.shared.keyWindow?.rootViewController?.present(self.imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.imagePicker.allowsEditing = false
UIApplication.shared.keyWindow?.rootViewController?.present(self.imagePicker, animated: true, completion: nil)
}))
//alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
//}
}
I've searched for this so this is why I tried UIApplication.shared.keyWindow?.rootViewController and also tried to run it from DispatchQueue.main.async but some how UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) is not working.
UPDATE If I push the view controller then it works. But I need a solution for presented view controller.
I would strongly recommend refactoring the whole solution to use delegates - delegate the action of presenting the alert from UITableViewCell to OrderFormViewController, and there simply use
self.present(alert, animated: true, completion: nil)
Because using UIApplication.shared.keyWindow?.rootViewController is really fragile.
So just to sketch it up for you, I believe the best approach is this:
class OrderFormViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
// set the delegate
cell.delegate = self
return cell
}
}
extension OrderFormViewController: CustomCellDelegate {
func customCellDelegateButtonPressed(_ customCell: CustomCell) {
let alert = UIAlertController(title: "Choose Image From", message: nil, preferredStyle: .alert)
// configure the alert
// now the presentation of the alert is delegated here to OrderFormViewController, so it can simply use self to present
self.present(alert, animated: true, completion: nil)
}
}
protocol CustomCellDelegate: class {
func customCellDelegateButtonPressed(_ customCell: CustomCell /*, potentially more parameters if needed */)
}
class CustomCell: UITableViewCell {
// rest omitted for brevity
weak var delegate: CustomCellDelegate?
#IBAction func cameraButtonPressed(_ sender: Any) {
delegate?.customCellDelegateButtonPressed(self)
}
}
class CoursesTableViewController: UITableViewController {
var nameOfCourse = "";
#IBAction func newCourse(_ sender: AnyObject) {
//1. Create the alert controller.
// var nameOfCourse = "";
let alert = UIAlertController(title: "New Course", message: "Enter the course name.", preferredStyle: .alert);
//2. Add the text field. You can configure it however you need.
alert.addTextField(configurationHandler: { (textField) -> Void in
textField.placeholder = ""
})
//3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
let textField = alert.textFields![0] as UITextField
self.nameOfCourse = textField.text!
print(self.nameOfCourse)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cells = tableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath) as? CoursesTableViewCell
cells?.textLabel.text = self.nameOfCourse
return cells!
}
Reload the table view after you've successfully set nameOfCourse (below print(self.nameOfCourse)).
Then I am trying to call action sheet when cell is tapped, and this is what I did
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alertController = UIAlertController(title: "Action Sheet", message: "What do you like to do", preferredStyle: .alert)
let okButton = UIAlertAction(title: "Done", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
let deleteButton = UIAlertAction(title: "Skip", style: .destructive, handler: { (action) -> Void in
print("Delete button tapped")
})
alertController.addAction(okButton)
}
When i am tapping cell, alert controller is not showing up. What am I missing?
You're almost there, make sure you add your deleteButton-action as well and present the alertController using present(alertController, animated: true, completion: nil)
Your action sheet does not show, because you are not presenting it.
present(alertController, animated: true /** or false */, completion: nil)
We create a function didSelectContact, and use func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) to handle selected Cell in tableview. If each cell tapped this action sheet will open.
func didSelectContact(){
let alert = UIAlertController(title: "Choose Once", message: "What you want do with contact", preferredStyle: UIAlertControllerStyle.actionSheet)
let call = UIAlertAction(title: "Call", style: UIAlertActionStyle.default) { (UIAlertAction) in
}
let sms = UIAlertAction(title: "SMS", style: UIAlertActionStyle.default) { (UIAlertAction) in
}
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(call)
alert.addAction(sms)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath) {
self.didSelectContact()
}
I want to update my tableview cells after an action is called in the editactionsForRowAtIndexPath function.
I've tried calling self.tableView.reloadData from the action handler, from the viewwillappear function and several other areas but it never reloads after the action is called.
What happens is a user swipes left and then they click the Confirm button which confirms an appointment and updates a value in the database.
The object is to have the function finish updating the value and then update the table by reloading so that in the cellforRowAtIndex can recycle through and color each cell a different color according to the values in the database.
But nothing seems to work.
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction] {
//confirm appointment
let confirm_action = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Confirm", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
self.index_number = indexPath.row
let confirm_menu = UIAlertController(title: nil, message: "Which request?", preferredStyle: .ActionSheet)
let number_1 = UIAlertAction(title: "Choice 1", style: UIAlertActionStyle.Default, handler: self.confirm1)
let number_2 = UIAlertAction(title: "Choice 2", style: UIAlertActionStyle.Default, handler: self.confirm2)
let number_3 = UIAlertAction(title: "Choice 3", style: UIAlertActionStyle.Default, handler: self.confirm3)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
confirm_menu.addAction(number_1)
confirm_menu.addAction(number_2)
confirm_menu.addAction(number_3)
confirm_menu.addAction(cancel)
self.presentViewController(confirm_menu, animated: true, completion: nil)
self.tableView.reloadData()
})
return [confirm_action]
}
//confirm choice1
func confirm1(alertAction: UIAlertAction!) -> Void {
tableView.sectionIndexColor = UIColor.greenColor()
//Update database entry to confirmed
let query = PFQuery(className: "Schedule")
query.getObjectInBackgroundWithId(object_ids[index_number]){
(Schedule: PFObject?, error: NSError?) -> Void in
//successfully loaded schedule request
if(error == nil && Schedule != nil) {
Schedule!["confirmed"] = "yes1"
dispatch_async(dispatch_get_main_queue()){
Schedule!.saveInBackground()
}
}
}
//update table
self.tableView.reloadData()
index_number = 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("schedules", forIndexPath: indexPath)
//load cell text depending on confirmed or not
if(confirmed_status[indexPath.row] == "yes1"){
cell.textLabel?.text = "\(users_names[indexPath.row]) \nPAID: \(paid_status[indexPath.row]) \nConfirmed for: \(location1) on \(date1)"
cell.textLabel!.textColor = UIColor.greenColor()
cell.editingStyle
}
else{
cell.textLabel?.text = "\(users_names[indexPath.row]) \nPAID: \(paid_status[indexPath.row]) \n#1 \(location1) on \(date1) \n#2 \(location2) on \(date2) \n#3 \(location3) on \(date3)"
}
//To enable word wrap for long titles
cell.textLabel!.numberOfLines = 0
return cell
}