본문 바로가기
iOS/iOS

CustomView

by 패쓰킴 2022. 2. 23.
728x90

File's Owner 기준으로 작성하였습니다.

file's owner =  말그대로 이 xib 파일의 주인을 말하며 이 파일에 구현되는 view는 file's owner의 클래스를 따르고,

분리되어 작성된다고 이해하면 됩니다.

 

화면을 분리하여 재사용성을 높이고 유연한 코드 유지 보수가 가능합니다.

 

준비

1. customView의 내용을 담을 .swift 파일 생성

2. customView UI를 만들 .xib 파일 생성

3. storyboard에 가져다 쓸 뷰이기 때문에 사이즈와 레이아웃에 제약을 받지 않기 위해 safeArea와 size 속성을 변경한다.

 

File's Owner의 File inspector - Interface Builder Document의 'Use Safe Area Layout Guides' 비활성화

View의 Attributes inspector - Simulated Metrics - size를 Freeform으로 변경

초기화

1. xib파일을 로드하기 위한 초기화 함수를 작성한다.

private func commonInit() {
  let bundle = Bundle.init(for: self.classForCoder)
  let view = bundle.loadNibNamed("내가 생성한 swift 파일의 클래스 이름",
                                 owner: self, options: nil)?.first as! UIView
  view.frame = self.bounds
  self.addSubview(view)
}

 

 - classForCoder : 나 자신의 클래스를 리턴해주는 프로퍼티

 - .first : File's Owner에는 여러개의 view가 들어갈 수 있기 때문에 정확히 어떤 view를 사용하려는지 지정해준다.

 

 

2. 작성한 초기화 함수를 내 view가 불릴 때 생성해주기 위한 코드를 작성한다.

// 코드로 초기화 할 때 사용
override init(frame: CGRect) {
  super.init(frame: frame)
  self.commonInit()
}

// 스토리보드로 초기화 할 때 사용
required init?(coder aDecoder: NSCoder) {
  super.init(coder: aDecoder)
  self.commonInit()
}

 

뷰 그리기, 기능 구현 _ UIButton을 올려보았다

1. .xib파일의 view에 버튼을 올리고 

2. .swift파일의 클래스 위에 '@IBDesignable'을 추가해주고

3. view의 버튼을 IBAction 연결 해주고

4. 버튼을 눌렀을 때 작동될 기능을 작성해준다.

 

뷰 연결하기

1. Main.storyboard에 view를 하나 올리고

2. 오토레이아웃을 적용하고

3. view의 identity inspector - Custom Class - Class에 내 커스텀뷰 클래스를 설정 해준다.

 

이제 실행 해서 버튼을 눌러보면 정상 동작하는 것을 확인 할 수 있다.

 

CustomView class 전체 코드

@IBDesignable
class CustomView: UIView {
    
  override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInit()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.commonInit()
  }

  private func commonInit(){
    let bundle = Bundle.init(for: self.classForCoder)
    let view = bundle.loadNibNamed("CustomView", owner: self, options: nil)?.first as! UIView
    view.frame = self.bounds
    self.addSubview(view)
  }
    
  @IBAction func tapMyBtn(_ sender: Any) {
    print("핼로핼로헬")
  }
}

 

예제 프로젝트 -> https://github.com/NORIKIM/Swift-TIL/tree/master/PracticeProject/CustomView

 

참고:

https://dev.to/ingun37/uiview-file-s-owner-2a20

https://daddy73e.tistory.com/2

https://developer.apple.com/documentation/objectivec/nsobject/1411876-classforcoder

https://dongminyoon.tistory.com/50

https://developer.apple.com/documentation/uikit/uinib/1614137-instantiate

 

728x90

'iOS > iOS' 카테고리의 다른 글

UIButton 상태에 따른 속성 적용(storyboard)  (0) 2022.02.24
JSON ecdoing / decoding  (0) 2022.02.24
ERROR 모음  (0) 2022.02.17
타이머  (0) 2022.01.25
아이폰 노치 여부 확인 방법  (0) 2022.01.24

댓글