본문 바로가기

IOS

IOS, Swift, Xcode - Basic App - ToDoList 단계별 뽀개기[1] - UIKit

728x90
반응형

https://youtu.be/Vqo36o9fSMM

//
//  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/about_app_development_with_uikit#overview

 

Apple Developer Documentation

 

developer.apple.com

import UIKit

UIKit는 프레임워크다.

iOS와 tvOS에 들어가는 앱을 빌드하는 데 필요한 핵심 오브젝트를 지원한다.

 

모든 UIKit앱은 app icons와 Launch screen storyboard를 필수적으로 가져야하낟.

app icons: The system displays your app icon on the home screen, in SEttings, and anywhere it needs to differentiate your app from other apps

The LaunchScreen: storyboard file contains your app's initial user interface, and it can be a splash scrren or a simplified version of your actual interface

 

Core Sturcture of UIKit App

UIKit provides many of your app's core objects, including those that interact with the system, run the app's main event loop, and display your content onscreen. You use most of there objects as-is or with only mminor modifications. Knowing which objects to modify, and when to modify them, is crucial to implementing your app.

 

Teh structure of UIKit apps is based on the Model_View_Controller (MVC) design patter, wherein objects are divided by their purpose. Model objects manage the app's data and business logic. View objects provde the visual representation of your data. Controller objects act as a bridge between your model and view objects, moving data between them at appropriate times.

UIKit Model

 

UIKit 앱의 구조는 MVC 디자인 패턴을 기반으로 한다.

메인 이벤트 루프를 실행하고 화면에 콘텐츠를 표시하며 여러 오브젝트를 제공하는데 적절한 시간에 데이터를 이동시키며 상호작용을 하는것이 핵심이다.

반응형