본문 바로가기

iOS (스파르타)/앱 개발 입문

코드베이스 작성

코드만으로 UI를 구성하기 위해 프로젝트에서 스토리보드를 완전히 삭제

 

1. Main 스토리보드 삭제. Move to Trash 로 삭제

 

2. info.plist 파일에서 Main 삭제 

 

3. 프로젝트 파일에서 TARGETS 선택 후 Build Settings로 이동 main 검색 후 삭제

 

4. 앱에게 맨 처음 시작할 뷰를 알려줘야 하므로 SceneDelegate.swift 파일에 코드 작성

 

// SceneDelegate.swift

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
		// 윈도우. 앱에 반드시 한 개는 필요한 가장 근본이 되는 뷰. 이 위에 뷰가 쌓이기 시작.
    var window: UIWindow?

		// 앱을 시작할때 세팅해줄 코드를 작성하는 곳.
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // UIWindow 객체 생성.
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        
        // window 에게 루트 뷰 지정. 
        window.rootViewController = ViewController()
        
         // 이 메서드를 반드시 작성해줘야 윈도우가 활성화 됨.
        window.makeKeyAndVisible()
        self.window = window
    }

 

5. 실행해 봤을 때 컴파일 에러없이 잘 실행되면 스토리보드 삭제 및 코드베이스 UI 작성 준비 완료.

 

 

NSLayoutConstraint 

 

https://developer.apple.com/documentation/uikit/nslayoutconstraint

 

NSLayoutConstraint | Apple Developer Documentation

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.

developer.apple.com

-읽어보기

 

 ▪️ NSLayoutConstraint를 이용해서 UILabel 그려보기.

  • let label = UILabel() 코드로 라벨을 선언.
  • configureUI()라는 메서드를 정의하고, 그 안에 UI를 세팅하는 코드들을 담습니다.
  • view는 ViewController가 기본적으로 갖고 있는 기본 view를 의미.
  • view에 label을 추가해야 합니다. view.addSubview(label) // 이 코드를 작성하지 않으면 라벨이 보이지 않음
  • 코드로 여러 가지 속성들을 부여. text, textColor 등.
  • label.translatesAutoresizingMaskIntoConstraints = false 이 코드는 오토 레이아웃을 활성화시키기 위해 작성 필요.
  • NSLayoutConstraint.activate 안에 제약조건들을 작성. 

 

 

configureUI 

일반적으로 "사용자 인터페이스(UI)를 설정하고나 구성한다"는  의미로 사용된다. 이 메서드는 보통 코드에서 UI요소들의 초기 설정, 레이아웃 배치, 스타일 지정 등을 수행한다.