Skip to content

Instantly share code, notes, and snippets.

@andhikayuana
Created January 27, 2020 12:02
Show Gist options
  • Save andhikayuana/5030f2cdd601f792deac84da50a4a8fc to your computer and use it in GitHub Desktop.
Save andhikayuana/5030f2cdd601f792deac84da50a4a8fc to your computer and use it in GitHub Desktop.
ios coredata
//
// ViewController.swift
// HitList
//
// Created by Andhika Yuana on 27/01/20.
// Copyright © 2020 Andhika Yuana. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//let ROW_IDENTIFIER = "Cell"
@IBOutlet weak var tableView: UITableView!
var names: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "The List"
tableView.register(
UITableViewCell.self,
forCellReuseIdentifier: "Cell"
)
}
@IBAction func addName(_ sender: UIBarButtonItem) {
let alert = UIAlertController(
title: "New Name",
message: "Add a new name",
preferredStyle: .alert
)
let saveAction = UIAlertAction(
title: "Save",
style: .default
) {
[unowned self] action in
guard let textField = alert.textFields?.first,
let nameToSave = textField.text else {
return
}
self.names.append(nameToSave)
self.tableView.reloadData()
print(self.names)
}
let cancelAction = UIAlertAction(
title: "Cancel",
style: .default
)
alert.addTextField()
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
}
//MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return names.count
}
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "Cell",
for: indexPath
)
cell.textLabel?.text = names[indexPath.row]
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment