-
[iOS] 3주차 세미나 정리iOS 2022. 10. 3. 19:34
01) 미션검사 및 피드백
위처럼 화면 구현할때 컴포넌트 계층을 먼저 나누고 설계하기 (ex. 어떤 레이아웃 배치할지)
동일한 UI 요소가 반복될때 (동일한 이미지, 텍스트 반복)
- collection view 이용 (4주차에서 자세하게 다룰 예정이지만, 예습해오기!)
+ 추가
- 이미지를 이미지에셋에 넣을때, 이미지 파일의 크기가 적절하지않아서 이미지 크기 변경에 대한 어려움 해결방안
에셋에 넣기전에 이미지 크기조절하고 넣어도되지만, 에셋에 넣기전에 이미지 크기 조절하기 어려우면 코드 사용으로 이미지 크기 조절이 가능하다!
이미지를 UI이미지로 활용할떄, UI 이미지 크기를 렌더링하면서 조절할수있다!
키워드 : UI image resize로 구글에 검색하기!
- 큰 디바이스에서는 잘 나오는데, 작은 디바이스에서는 화면에 적절하게 나오지않는 문제점
위 속성에서
relation값을 less than or equal로 바꿔주면 레이아웃을 활용할 수 있다!
+ 화면전환
- present
한 화면에서 이 화면에 대한 추가적인 내용을 보여줄때
// typecasting (opitonal 이용) guard let presentedViewController = UIStoryboard(name : "Main", bundle:nil).instantiateViewController(withIdentifier: "presentedViewController") as? presentedViewController else {return} present(presentedViewController, animated: true)
- navigation
아예 다음 페이지로 넘어갈때
cf) back 버튼이 자동으로 생성된다.
guard let pushedViewController = UIStoryboard(name : "Main", bundle:nil).instantiateViewController(withIdentifier: "pushedViewController") as? pushedViewController else {return} navigationController?.pushViewController(pushedViewController, animated: true)
상황에 따라 선택적으로 판단해서 사용하기!
02) view life cycle 이론
우리가 평소 생각하는 생명주기란 무엇인가?
- 생명의 한 사이클
그렇다면 View에게 생명주기란 무엇인가?
- 탄생하고부터 소멸하기까지의 한 과정 (화면에 보여졌다가 사라지기까지의 과정)
4가지의 사이클
- 나타남, 사라지는 중, 사라짐, 나타나는 중
- 각각의 메서드가 존재함
일상생활에서 생명주기란 단어를 사용하듯이 iOS개발에도 view에 대한 생명주기라는 단어를 사용하는데 메서드를 통해 사용하고 있다.
총 8단계로 라이프 사이클 단계를 세분화 - init : 사람으로 따지면 신생아가 태어날 때 순간 view로 따지면 생성되는 단계
-loadView : 사람으로 따지면 태어나고 아기가 태어났다는 소식을 들은 순간
-viewDidLoad : 정의를 내려보면 view계층이 새로 메모리에 호출된후 생성되는것인데, 사람으로 따지면 아기가 태어나고 출생신고할때
(메모리에 호출된 직후 호출되는 메서드)
생명주기는 애플에서 8단계로 구분해놨고, 활용될수있는 메서드를 애플에서 기본적으로 제공하고있다!
왜 생명주기를 다루게 되었을까?
- 시대가 지나고 새로운 개발 기술이 나오면서, 컴퓨터에서 하던작업을 모바일에서도 작업이 가능하게 시대가 발전하고 있다.
- 이러면서 한가지 딜레마가 발생되는데, 모니터에서 보여지던 화면을 스마트폰에 압축해서 보여지게 하는 작업을 할때, 모니터에 나타나는 화면이 스마트폰에는 한번에 나오지않게 되는 문제가 발생하게 된다.
ex) 회원가입 화면
이에 한 화면에서 하던 화면을 여러단계로 쪼개다보니 뷰의 전환이 많아짐에 따라 이 뷰 전환에 과정에서 따로 개발적으로 코드를 작성해야되는 상황이 많아져서 생명주기를 다루게되었다.
03) View life Cycle 실습 + App Life Cycle
View life Cycle
// // ViewController.swift // week3_LifeCycle // // Created by 김민경 on 2022/10/03. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("viewDidLoad\n") // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("viewWillAppear\n") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("viewDidAppear\n") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("viewWillDisappear\n") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("viewDidDisappear\n") } }
- 버튼을 눌렀을때, 텍스트필드에 있는 값이 더해져서 다음 화면에 뜨게하기
// // ViewController.swift // week3_LifeCycle // // Created by 김민경 on 2022/10/03. // import UIKit class ViewController: UIViewController { @IBOutlet weak var firstTextField: UITextField! @IBOutlet weak var secondTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() //print("viewDidLoad\n") // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("viewWillAppear\n") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("viewDidAppear\n") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("viewWillDisappear\n") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("viewDidDisappear\n") } //화면 전환 @IBAction func buttonDidTap(_ sender: Any) { // typecasting (opitonal 이용) guard let nextViewController = UIStoryboard(name : "Main", bundle:nil).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else {return} // 덧셈을 해서 다음 뷰에 넘기는 로직 guard let firstNumber=firstTextField.text else {return} guard let secondNumber=secondTextField.text else {return} // 덧셈 결과 담기 (optional : ! 이용, guard문을 사용하는게 더 안전하긴함) let result = Int(firstNumber)! + Int(secondNumber)! nextViewController.resultString = String(result) // 덧셈의 결과를 담는다. nextViewController.modalPresentationStyle = .fullScreen present(nextViewController, animated: true) } }
화면이 사라지는게 아니므로, 아래 함수가 실행되지않는다.
override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("viewWillDisappear\n") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("viewDidDisappear\n") }
// // SecondViewController.swift // week3_LifeCycle // // Created by 김민경 on 2022/10/03. // import UIKit class SecondViewController: UIViewController { // 덧셈의 결과를 담을 변수 선언 var resultString="default 값" // 덧셈의 결과가 담길 예정 @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() resultLabel.text = resultString // 덧셈의 결과 // Do any additional setup after loading the view. } // 생명주기 전 단계이므로 viewWillAppear에서 처리해도 문제없음 // override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // resultLabel.text = resultString // 덧셈의 결과 // } }
- View life Cycle 화면 출력 확인 (fullscreen일때와 아닐때 비교)
해당 코드를 추가해주어 fullScreen으로 바꿔주면
nextViewController.modalPresentationStyle = .fullScreen
viewWillDisappear와 viewDidDisappear가 뜨는걸 볼수있다.
App Life Cycle
앱도 view처럼 라이프 사이클을 갖는다!
// // SceneDelegate.swift // week3_LifeCycle // // Created by 김민경 on 2022/10/03. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). print("sceneDidDisconnect") // 앱이 꺼짐 } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. print("sceneDidBecomeActive") } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). print("sceneWillResignActive") // 앱이 곧 비활성화될것이다! } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. print("sceneWillEnterForeground") } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. print("sceneDidEnterBackground") // 앱이 백그라운드 상태에 도입했을때 } }
04) 미션안내
- 스탠다드 미션
덧셈말고 기본적으로 스위프트 문법을 활용해서 사칙연산(+, -, %,,,등등) 을 이용해 화면 넘기기 (버튼 로직에 추가하기)
화면전환할때, navigation으로 활용해보기!
- 챌린지 미션
라이플 사이클 활용해서 메모장 앱 만들기 (생명주기가 여러단계가 활용됨 - 앱을 나갔다 들어왔을때도 메모가 남아있어야하는 등)
+ 추가
스스로 보완을 해서 세상에 존재하지않는 나만의 앱을 만들기 (게임, 서비스 등 화면전환과 뷰간의 데이터 주고받는것 활용해서 만들기)
TIP)
'iOS' 카테고리의 다른 글
[iOS] 4주차 세미나 정리 (0) 2022.10.28 [iOS] 간단한 계산기 만들기 (0) 2022.10.06 [iOS] 전화 기본앱 만들기 (0) 2022.09.29 [iOS] 2주차 세미나 정리 (0) 2022.09.27 [iOS] UI components 조사 (0) 2022.09.21