//
// ViewController.swift
// OurToDoList
//
// Created by JEONGGEUN LIM on 2023/01/10.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
// 테이블뷰 기본 UI 설정
private let table: UITableView = {
let table = UITableView()
table.register(UITableViewCell.self,
forCellReuseIdentifier: "cell")
return table
}()
var items = [String]() // 목록을 저장할 리스트
override func viewDidLoad() {
super.viewDidLoad()
self.items = UserDefaults.standard.stringArray(forKey: "items") ?? [] // 리스트를 저장할 수 있도록, 없다면 nil 리스트
title = "To Do List" // 타이틀 설정
view.addSubview(table)
table.dataSource = self // self as the class name(ViewController)
// alert
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(didTapAdd)) // 우측 상단의 + 버튼, didTapAdd 함수와 연결
}
// didTapAdd함수, + 버튼을 누를경우 실행
@objc private func didTapAdd(){
let alert = UIAlertController(title: "New Item", message: "Enter new to do list item!", preferredStyle: .alert)
alert.addTextField{ field in field.placeholder = "Enter item..."}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { [weak self](_) in // weak self는 메모리 leak를 예방
if let field = alert.textFields?.first {
if let text = field.text, !text.isEmpty{
DispatchQueue.main.async{ // 백그라운드에서도 실행될 수 있도록
var currentItems = UserDefaults.standard.stringArray(forKey: "items") ?? []
// let newEntry = [text]
currentItems.append(text)
// UserDefaults.standard.setValue(newEntry, forKey: "items") // 어플 종료 후에도 리스트가 남아있도록
UserDefaults.standard.setValue(currentItems, forKey: "items") // 작성했던 리스트가 남아있도록
self?.items.append(text)
self?.table.reloadData()
}
}
}
}))
present(alert, animated: true) // + 버튼 클릭시 알람 화면 출력
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
table.frame = view.bounds // 프레임에 맞춰서 바운더리 설정
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count // number of the row
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // "cell"이름으로 identifier
cell.textLabel?.text = items[indexPath.row]
return cell
}
}
https://developer.apple.com/documentation/uikit/uiviewcontroller/
The UIViewController class defines the shared behavior that's common to all view contorllers. You rarely create instances of the UIViewController calss directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.
UIViewController는 모든 view controller에게 공통적으로 사용될 동작을 정의하고있으며 상속받으며 사용하는 경우가 대부분이다.
상속받은 자식클래스는 계층 구조를 관리할 메서드를 정의한다.
A view controller's main responsibilities include the following:
1. Updating the contents of the views, usually in response to changes to the underlying data
입력된 데이터에 따른 view 업데이트
2. Responding to user interactions with views
유저의 입력과 view의 상호작용
3. Resizing views and managing the layout of the overall interface
전반적인 인터페이스와 레이아웃의 범위 조절
4. Coordinating with other objects = including other view controllers - in your app
다른 object들과의 view controller를 통한 상호작용
'IOS' 카테고리의 다른 글
iOS Beginner Challenge Lesson4 by CodewithChris (0) | 2023.01.16 |
---|---|
Swift - 클로저 {} by yagom (0) | 2023.01.11 |
IOS, Swift, Xcode - Basic App - ToDoList 단계별 뽀개기[1] - UIKit (0) | 2023.01.11 |
IOS, Swift, Xcode를 배우기 시작하면서 (0) | 2023.01.10 |
swift - 고차함수 by yagom (1) | 2023.01.10 |