본문 바로가기
ios 뽀개기/실전

메모장 - 커스텀(x)

by 인생여희 2018. 1. 3.
반응형

메모장 - 커스텀(x)


//


//  AppDelegate.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit

import CoreData


@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {


    var window: UIWindow?

    

    //접근성과 일관성 데이터 보존의 이유로 이곳에 작성

    var memolist = [MemoData]() //메모 데이터를 저장할 배열 변수 - 여러개의 메모를 목록형식으로 저장할 것임

    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Override point for customization after application launch.

        return true

    }


    func applicationWillResignActive(_ application: UIApplication) {

        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

    }


    func applicationDidEnterBackground(_ application: UIApplication) {

        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    }


    func applicationWillEnterForeground(_ application: UIApplication) {

        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    }


    func applicationDidBecomeActive(_ application: UIApplication) {

        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    }


    func applicationWillTerminate(_ application: UIApplication) {

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

        // Saves changes in the application's managed object context before the application terminates.

        self.saveContext()

    }


    // MARK: - Core Data stack


    lazy var persistentContainer: NSPersistentContainer = {

        /*

         The persistent container for the application. This implementation

         creates and returns a container, having loaded the store for the

         application to it. This property is optional since there are legitimate

         error conditions that could cause the creation of the store to fail.

        */

        let container = NSPersistentContainer(name: "Real")

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in

            if let error = error as NSError? {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                 

                /*

                 Typical reasons for an error here include:

                 * The parent directory does not exist, cannot be created, or disallows writing.

                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.

                 * The device is out of space.

                 * The store could not be migrated to the current model version.

                 Check the error message to determine what the actual problem was.

                 */

                fatalError("Unresolved error \(error), \(error.userInfo)")

            }

        })

        return container

    }()


    // MARK: - Core Data Saving support


    func saveContext () {

        let context = persistentContainer.viewContext

        if context.hasChanges {

            do {

                try context.save()

            } catch {

                // Replace this implementation with code to handle the error appropriately.

                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                let nserror = error as NSError

                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")

            }

        }

    }


}



//

//  MemoData.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import Foundation

import UIKit


class MemoData  {

    

    var memoIdx : Int? //데이터 식별값

    var title : String? //제목

    var contents : String? //내용

    var image : UIImage? //이미지

    var regdate: Date? //작성일

    

}




//

//  MemoCell.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit


class MemoCell: UITableViewCell {


   

    @IBOutlet var subject: UILabel! //메모 제목

    

    @IBOutlet var contents: UILabel! // 메모 내용

    

    @IBOutlet var regdate: UILabel! // 등록 일자

    

    @IBOutlet var img: UIImageView! // 이미지

    

}


//

//  MemoFormVC.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit


class MemoFormVC: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITextViewDelegate {

    var subject: String! //제목을 저장하는 역할

    @IBOutlet var contents: UITextView!

    @IBOutlet var preview: UIImageView!


    func textViewDidChange(_ textView: UITextView) {

        //내용의 최대 15자리 까지 읽어 subject변수에 저장한다.

        let contents = textView.text as NSString

        let length = ((contents.length > 15) ? 15 : contents.length)

        self.subject = contents.substring(with: NSRange(location:0, length: length))

        self.navigationItem.title = subject

    }

    

    

    

    override func viewDidLoad() {

        super.viewDidLoad()


        self.contents.delegate = self

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    //저장

    @IBAction func save(_ sender: Any) {

        

        

        //내용을 입력하지 않았을 경우, 경고한다.

        

        guard self.contents.text?.isEmpty == false else{

            

            let alert = UIAlertController(title:nil,

                                          message:"내용을 입력해주세요",

                                          preferredStyle:.alert)

            alert.addAction(UIAlertAction(title:"ok",style:.default, handler:nil))

            self.present(alert,animated: true)

            return

            

        }

        

        //메모 데이터에 저장

        let data = MemoData()

        data.title = self.subject

        data.contents = self.contents.text

        data.image = self.preview.image

        data.regdate = Date()

        

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        appDelegate.memolist.append(data)

        

        _ = self.navigationController?.popViewController(animated: true)

        

        

    }

    

    //사진 가져오기

    @IBAction func pick(_ sender: Any) {

    //이미지 피커 인스턴스 생성

    let picker = UIImagePickerController()

    //이미지 피커 컨트롤러 인스턴스의 델리게이트 속성을 현재의 뷰 컨트롤러 인스턴스로 설정

    picker.delegate = self

    //이미지 편집 허용

    picker.allowsEditing = true

    //이미지 피커 화면을 표시한다

    self.present(picker, animated: false)

    }

    //이미지 선택을 완료했을 때 호출되는 메소드

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        //선택된 이미지를 미리보기에 표시

        self.preview.image = info[UIImagePickerControllerEditedImage] as? UIImage

        //이미지 피커 컨트롤러를 닫는다.

        picker.dismiss(animated: false)

    }

    

}


//

//  MemoListVC.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit


class MemoListVC: UITableViewController {

    

    //앱델리게이트 객체의 참조 정보를 읽어 온다.

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    

     //테이블 데이터를 다시 읽어들인다. 이에 따라 행을 구하는 로직이 다시 실행된다. / 해당뷰컨트롤러가 디바이스의 스크린에 출력될때마다 호출된다.

    override func viewWillAppear(_ animated: Bool) {

        // 다른 화면으로 이동했다가 목록으로 돌아왔을때,

        // 홈버튼을 눌러 앱이 백그라운드 모드로 내려간 후 다시 활성화되었을 때

        // 키타 상황으로 뷰 컨트롤러가 스크린에 표시될 때

       self.tableView.reloadData()

    }

    

    //테이블 행의 개수를 결정하는 메소드

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let count = self.appDelegate.memolist.count

        return count

    }


   //테이블 행을 구성하는 메소드

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        //1. memolist 배열 데이터에서 주어진 행에 맞는 데이터를 꺼낸다.

        let row = self.appDelegate.memolist[indexPath.row]

        

        //2. 이미지 속성이 비어 있을 경우 "memoCell" 아니면 "memoCellWidthImage"

        let cellId = row.image == nil ? "memoCell" : "memoCellWithImage"

        

        //3.재사용 큐로 부터 프로토타입 셀의 인스턴스를 전달 받는다.

        let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? MemoCell

        

        //4. memoCell의 내용을 구성한다.

        cell?.subject?.text = row.title

        cell?.contents?.text = row.contents

        cell?.img?.image = row.image

        

        //5. Date 타입의 날짜를 yyyy-MM-dd HH:mm:ss 포멧에 맞게 변경한다.

        let formatter = DateFormatter()

        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        cell?.regdate?.text = formatter.string(from: row.regdate!)

        

        return cell!

    }


    

    //테이블의 특정 행이 선택되었을 때 호출되는 메소드, 선택된 행의 정보는 indexpath에 담겨 있다.

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        

        //1. memoList 배열에서 선택된 행에 맞는 데이터를 꺼낸다.

        let row = self.appDelegate.memolist[indexPath.row]

        

        //2.상세 화면의 인스턴스를 생성한다.

        guard let vc = self.storyboard?.instantiateViewController(withIdentifier: "MemoRead") as? MemoReadVC else {

            return

        }

        //3.값을 전달한 다음, 상세화면으로 이동한다.

        vc.param = row

        self.navigationController?.pushViewController(vc, animated: true)

    }

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


}


//

//  MemoReadVC.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit


class MemoReadVC: UIViewController {

    

    //콘텐츠 데이터를 저장하는 변수

    var param : MemoData?

    

    @IBOutlet var subject: UILabel!

    

    @IBOutlet var contents: UILabel!

    

    @IBOutlet var img: UIImageView!

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        self.subject.text = param?.title

        self.contents.text = param?.contents

        self.img.image = param?.image

        

        let formatter = DateFormatter()

        formatter.dateFormat = "dd일 HH:mm분에 작성됨"

        let dateString = formatter.string(from: (param?.regdate)!)

        

        self.navigationItem.title = dateString

        

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    


}


//

//  MemoFormVC.swift

//  Real

//

//  Created by MacBookPro on 2017. 12. 29..

//  Copyright © 2017년 MacBookPro. All rights reserved.

//


import UIKit


class MemoFormVC: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITextViewDelegate {

    var subject: String! //제목을 저장하는 역할

    @IBOutlet var contents: UITextView!

    @IBOutlet var preview: UIImageView!


    func textViewDidChange(_ textView: UITextView) {

        //내용의 최대 15자리 까지 읽어 subject변수에 저장한다.

        let contents = textView.text as NSString

        let length = ((contents.length > 15) ? 15 : contents.length)

        self.subject = contents.substring(with: NSRange(location:0, length: length))

        self.navigationItem.title = subject

    }

    

    

    

    override func viewDidLoad() {

        super.viewDidLoad()


        self.contents.delegate = self

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    //저장

    @IBAction func save(_ sender: Any) {

        

        

        //내용을 입력하지 않았을 경우, 경고한다.

        

        guard self.contents.text?.isEmpty == false else{

            

            let alert = UIAlertController(title:nil,

                                          message:"내용을 입력해주세요",

                                          preferredStyle:.alert)

            alert.addAction(UIAlertAction(title:"ok",style:.default, handler:nil))

            self.present(alert,animated: true)

            return

            

        }

        

        //메모 데이터에 저장

        let data = MemoData()

        data.title = self.subject

        data.contents = self.contents.text

        data.image = self.preview.image

        data.regdate = Date()

        

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        appDelegate.memolist.append(data)

        

        _ = self.navigationController?.popViewController(animated: true)

        

        

    }

    

    //사진 가져오기

    @IBAction func pick(_ sender: Any) {

    //이미지 피커 인스턴스 생성

    let picker = UIImagePickerController()

    //이미지 피커 컨트롤러 인스턴스의 델리게이트 속성을 현재의 뷰 컨트롤러 인스턴스로 설정

    picker.delegate = self

    //이미지 편집 허용

    picker.allowsEditing = true

    //이미지 피커 화면을 표시한다

    self.present(picker, animated: false)

    }

    //이미지 선택을 완료했을 때 호출되는 메소드

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        //선택된 이미지를 미리보기에 표시

        self.preview.image = info[UIImagePickerControllerEditedImage] as? UIImage

        //이미지 피커 컨트롤러를 닫는다.

        picker.dismiss(animated: false)

    }

    

}



반응형

'ios 뽀개기 > 실전' 카테고리의 다른 글

alert 커스텀 - 지도1  (0) 2018.01.03
alert 커스텀 - 기본  (0) 2018.01.03
커스텀 내비게이션 바  (0) 2018.01.03
탭바 커스텀하기  (0) 2018.01.02
커스텀 버튼 및 데이터 전달하기  (0) 2018.01.02

댓글