Swipe like Trash button Of Mail on iOS - Swift 2 - ios

I'm working on an app, and would like the swipe was equal to swipe of Trash of Mail iOS:
My ViewController has a TableView:
And my Swift code:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var arr = [NSMutableDictionary]()
var count:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCell
let row = self.arr[indexPath.row]
cell.label.text = row["name"] as? String
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let alert = UIAlertController(title: "Remove?", message: "Touch in Remove", preferredStyle: .Alert)
let remove = UIAlertAction(title: "Remove", style: UIAlertActionStyle.Destructive) { (UIAlertAction) -> Void in
self.arr.removeAtIndex(indexPath.row)
self.tableView.reloadData()
}
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alert.addAction(cancel)
alert.addAction(remove)
self.presentViewController(alert, animated: true,completion: nil)
}
}
#IBAction func addAction(sender: AnyObject) {
arr.append(["name":"row \(count)","age":"23"])
++count
self.tableView.reloadData()
}
}
When I preview the app, I see the swipe that way:
My question is: What do I need to make my app swipe equal to swipe Mail Trash?

You should use the delegate method
'titleForDeleteConfirmationButtonForRowAtIndexPath'
and return the string value (in your case "Trash") that you wish to display

Related

Delete not working and last value not display, User default with tableview

I implemented to save data in local using user dafaults with table view. when insert data every data display in my tableview. but stop and run again last value is not dispayed. and when swipe and remove not working when app run next time.
import UIKit
let defaults = UserDefaults(suiteName: "com.saving.data")
class HomeWorkViewController: UITableViewController {
var rows = [String]()
call getData() method in viewDidload
override func viewDidLoad() {
super.viewDidLoad()
getData()
// Do any additional setup after loading the view.
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
calling getData() method
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
getData()
}
calling storeData method
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
storeData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func addButton(_ sender: Any) {
addCell()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "homeWork", for: indexPath)
cell.textLabel?.text = rows[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
rows.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadData()
}else if editingStyle == .insert {
}
}
func addCell(){
let alert = UIAlertController(title: "Add Home Work", message: "Input text", preferredStyle: .alert)
alert.addTextField{(textField) in
textField.placeholder = "text...."
}
alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: {[weak alert](_) in
let row = alert?.textFields![0]
self.rows.append((row?.text)!)
self.tableView.reloadData()
}))
self.present(alert,animated: true, completion: nil)
storeData()
}
func storeData(){
defaults?.set(rows, forKey: "savedData")
defaults?.synchronize()
}
func getData(){
let data = defaults?.value(forKey: "savedData")
if data != nil {
rows = data as! [String]
}else{}
}
}
You call storeData() at the wrong place. The addAction closure is executed later in time.
func addCell() {
let alert = UIAlertController(title: "Add Home Work", message: "Input text", preferredStyle: .alert)
alert.addTextField{(textField) in
textField.placeholder = "text...."
}
alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: {[weak alert](_) in
let row = alert?.textFields![0]
let insertionIndex = self.rows.count
self.rows.append(row.text!)
self.tableView.insertRows(at: IndexPath(row: insertionIndex, section: 0), with: .automatic)
self.storeData()
}))
self.present(alert,animated: true, completion: nil)
}
And never call reloadData after calling deleteRows
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
rows.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
self.storeData()
}
}
And use the dedicated API of UserDefaults (don't call synchronize)
func storeData(){
defaults!.set(rows, forKey: "savedData")
}
func getData(){
rows = defaults!.array(forKey: "savedData") as? [String] ?? []
}

Popup alert user before delete TableViewCell in swift?

title basically says it; surprised I couldn't find anything on stack overview but none helped me or were in objective C
I have a table view with a list of items and an edit button that allows user to delete rows (can also 'swipe to delete'). basically, I want to have a popup alert that says "are you sure you want to delete (rowname)" where row name is the name of the row about to be deleted. from what I have found/tried, I can get the popup BUT it shows up every time you press the edit button or swipe right. I only want the popup to appear when the user presses "delete".
and, obviously, from the popup if they press Cancel it should cancel, if they press delete it should delete
how do you do this in general?
sorry I am kind of a noob
All you have to do is present the alert when the button is pressed and set each action.
Replace your commit editingStyle delegate method with this and replace the data variable with your data array:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
presentDeletionFailsafe(indexPath: indexPath)
}
}
func presentDeletionFailsafe(indexPath: IndexPath) {
let alert = UIAlertController(title: nil, message: "Are you sure you'd like to delete this cell", preferredStyle: .alert)
// yes action
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
// replace data variable with your own data array
self.data.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
alert.addAction(yesAction)
// cancel action
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
EDIT
Example:
private let reuseId = "cellReuseId"
class SlideToDeleteViewController : UIViewController {
lazy var tableView = createTableView()
func createTableView() -> UITableView {
let tableView = UITableView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseId)
tableView.dataSource = self
tableView.delegate = self
return tableView
}
var data = ["one", "two", "three", "four"]
override func loadView() {
self.view = tableView
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension SlideToDeleteViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId)
cell?.textLabel?.text = data[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
presentDeletionFailsafe(indexPath: indexPath)
}
}
func presentDeletionFailsafe(indexPath: IndexPath) {
let alert = UIAlertController(title: nil, message: "Are you sure you'd like to delete this cell", preferredStyle: .alert)
// yes action
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
// put code to remove tableView cell here
self.data.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
alert.addAction(yesAction)
// cancel action
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}

call by touching cell in Swift

i used Core Date to save names and phone numbers
i would like to make a call by touching cell
here is my code:
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var people = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
do {
let people = try PersistenceService.context.fetch(fetchRequest)
self.people = people
self.tableView.reloadData()
} catch {}
}
#IBAction func onPlusTapped() {
let alert = UIAlertController(title: "Add Person", message: nil, preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Name"
}
alert.addTextField { (textField) in
textField.placeholder = "Phone number"
textField.keyboardType = .numberPad
}
let action = UIAlertAction(title: "Post", style: .default) { (_) in
let name = alert.textFields!.first!.text!
let phoneNumber = alert.textFields!.last!.text!
let person = Person(context: PersistenceService.context)
person.name = name
person.phoneNumber = phoneNumber
PersistenceService.saveContext()
self.people.append(person)
self.tableView.reloadData()
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.textLabel?.text = people[indexPath.row].name
cell.detailTextLabel?.text = people[indexPath.row].phoneNumber
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
people.remove(at: indexPath.item)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIApplication.shared.openURL(NSURL(string: "tel://" + (people[indexPath.row].phoneNumber?.description)!)! as URL)
print(people[indexPath.row].phoneNumber?.description)
}
}
No need to add an #IBAction, you can use didSelectRow from UITableViewDelegate
You are already implementing the didSelectRowAt use IBActions only inside UITableView if you have a UIButton inside the UITableViewCell

UserDefaults in a UITableViewCell not saving (swift3)

My code right now just lists things you manually enter. However when the user switches view controllers the code disappears. I tried to use userdefualts to save my current code in the number of rows in selection function but it does not save the items in the tableview cells. I just want to save whatever is in the tableview cells.
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var items: [String] = [""]
#IBOutlet weak var listTableView: UITableView!
#IBAction func addItem(_ sender: AnyObject) {
alert()
}
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
listTableView.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listitem") as! ItemTableViewCell
cell.itemLabel.text = items[indexPath.row]
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let userDefaults = UserDefaults.standard
userDefaults.setValue(items, forKey: "items")
userDefaults.synchronize()
return items.count
}
func alert(){
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
alert.addTextField{
(textfield) in
textfield.placeholder = " Enter "
}
let add = UIAlertAction(title: "Add", style: .default){
(action) in
let textfield = alert.textFields![0]
self.items.append(textfield.text!)
self.listTableView.reloadData()
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
(alert) in
}
alert.addAction(add)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}}
You have a number of issues in your code:
You never load your data back from UserDefaults. - This is the big one
There is no need to call synchronise.
You should save your data when data is added/deleted, not in numberOfRowsInSection.
It will look nicer if you insert a new row rather than reloading the whole table
I would suggest something like:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var items = [String]()
#IBOutlet weak var listTableView: UITableView!
#IBAction func addItem(_ sender: AnyObject) {
alert()
}
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
listTableView.dataSource = self
self.items = UserDefaults.standard.stringArray(forKey:"items") ?? [String]()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listitem") as! ItemTableViewCell
cell.itemLabel.text = items[indexPath.row]
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func saveData() {
userDefaults.standard.set(items, forKey: "items")
}
func alert(){
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
alert.addTextField{
(textfield) in
textfield.placeholder = " Enter "
}
let add = UIAlertAction(title: "Add", style: .default){
(action) in
guard let textfield = alert.textFields?.first else {
return
}
if let newText= textfield.text {
self.items.append(newText)
saveData()
let indexPath = IndexPath(row: items.count - 1, section: 0)
self.listTableView.insertRows(at: [indexPath], with: .automatic)
}
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
(alert) in
}
alert.addAction(add)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
saveData()
}
}
Also, you shouldn't really use UserDefaults for data storage this way, but I presume this is just a simple learning exercise.

How to re-save data in UITableVIew without causing any duplicates of the same UITextVIew in Swift3

Userdefaults-saved data is passed from my TextViewCotroller to TextViewTableController successfully, but not perfectly successful. This is because when my TextView, which has some data already, is re-saved, it causes a duplicate.
For example, if the firstly saved data is like "hello, I like bagels" and if I edit it to like "hello, I like bagels and chololate cookies" and re-save it,
At the 0 index of my TableView is "hello, I like bagels and chololate cookies"
At the 1 index of my TableView is "hello, I like bagels"
When this is repeatedly done, there are multiple duplicates of the same text in my TableView. This is so annoying that I really want to detect the cause of this issue. However, I have no idea of fixing this bug.
TextTableViewController:
class TextTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
self.tableView.reloadData()
}
func saveTextData() -> [String] {
if let textData = userTextDataSave.array(forKey: "txtData") as? [String] {
return textData
}
return []
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return saveTextData().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellForText", for: indexPath)
cell.backgroundColor = UIColor.clear
cell.preservesSuperviewLayoutMargins = false
cell.textLabel?.text = saveTextData()[indexPath.row]
cell.textLabel?.font = UIFont.systemFont(ofSize: 20)
tableView.reloadData()
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
removeHistory(index: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "text",sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
if (segue.identifier == "text") {
let subVC: TextViewController = (segue.destination as? TextViewController)!
let indexPath = tableView.indexPathForSelectedRow;
subVC.textFromCell = saveTextData()[(indexPath?.row)!]
}
}
}
TextViewController and functions for saving text data:
func save(){
let alert = UIAlertController(title: "titile", message: "save?", preferredStyle: .alert)
let noAction = UIAlertAction(title: "Cancel", style: .default, handler: { Void in
})
let okAction = UIAlertAction(title: "Save", style: .default, handler: { Void in
self.addTextData(text: self.myTextView.text)
})
alert.addAction(noAction)
alert.addAction(okAction)
present(alert, animated: false, completion: nil)
}
func saveTextData() -> [String] {
if let textData = userTextDataSave.array(forKey: "txtData") as? [String] {
return textData
}
return []
}
func addTextData(text: String) {
var data = saveTextData()
for d in data {
if d == "" {
return
}
}
data.insert(text, at: 0)
userTextDataSave.set(text, forKey: "txtData")
userTextDataSave.synchronize()
}
Try this :
func addTextData(text: String) {
var data = saveTextData()
for d in data {
if d == "" {
return
}
if d == text {
return
}
}
userTextDataSave.set(text, forKey: text)
userTextDataSave.synchronize()
}

Resources