Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] xib로 ViewController 만들기 본문

iOS 기본 (swift)

[iOS - swift] xib로 ViewController 만들기

jake-kim 2021. 3. 22. 23:04

ViewController를 xib로 사용할때의 장점

  • xib는 재사용이 쉽지만, storyboard에 있는 ViewController를 재사용하려면 어려움
  • ViewController의 객체를 얻기가 쉬움
    :storyboard를 이용하면 storyboard객체를 통해 ViewController객체를 얻지만, xib는 nib이름만 있으면 가능

xib로 ViewController 사용 준비

  • xib 파일 생성: SampleVC.xib

  • swift파일 생성: SampleVC.swift
import Foundation
import UIKit

class SampleVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
  • .xib파일과 swit. 파일 연결

  • xib에서 View와의 outlet연결 (안할 경우 crash 발생 주의)

사용 방법

  • nib란? 인터페이스 빌더에서(xib) 구성해놓은 여러 시각적 요소 및 비시각적 요소에 대해서 개별적인 세팅값, 뷰의 위치, 색상, 폰트, 등을 시각적으로 구성해 놓고이들을 object-graph로 만든 정보를 직렬화한 파일
  • .swift파일의 생성자 init(nibName:bundle:)로 접근하여 ViewController객체 획득 (간편)
  • init(nibName:bundle:)에서 bundle이란?: xib파일이 있는 위치를 나타내며, 메모리 cache를 위한 값
let vc = LongPressedVC(nibName: "SampleVC", bundle: nil)
self.present(vc, animated: true, completion: nil)
  • bundle값에 nil로 해도 상관없지만 메모리를 cache하여 사용할 수 있게끔 bundle객체를 넣어주는것이 효율
let bundle = Bundlle(for: type(of: LongPressedVC))
let vc = LongPressedVC(nibName: "SampleVC", bundle: bundle)
self.present(vc, animated: true, completion: nil)

 

Comments