티스토리 뷰

거의 모든 상황에서 뷰를 만들때 재사용을 할 수 있도록 만듭니다.

왜냐면 디자인의 버튼을 예를 든다면 거의 비슷한 버튼이 나오죠...

 

그래서 CustomView를 하는 방법을 알아보도록 합시다.

 

저는 UIViewController에 이런걸 넣고 싶어요

 

그렇죠 My Name is DH 부분의 파란 배경까지가 CustomView 입니다.

 

사용할 File은 대략 이렇게 3개에요.

 

자 그럼 하나씩 봅시다.

 

1. CustomView

import UIKit

extension UIView {
    func loadView(nibName: String) -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
    
    var mainView: UIView? {
        return subviews.first
    }
}

@IBDesignable
class CustomView : UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    private func setup() {
        backgroundColor = .clear
        guard let view = loadView(nibName: "CustomView") else { return }
        view.frame = self.bounds
        self.addSubview(view)
    }
}

코드는 그렇게 어렵지 않습니다.

그냥 init 두개의 부분에 setup을 불러주는데 그 안에서 nib를 이름으로 불러서 가져오게 합니다.

 

extension을 이용하여 UIView에 func을 만들어주고 mainView를 넣어주는데요. 이건 가정상 subview의 첫번째 뷰가 load된 View라고 가정하는 겁니다.

 

2. CustomView.xib

넓게 찍어서 잘 보이실지 모르겠네요.

보면 File's Owner를 이 xib가 바라볼 Class Name을 지정하여 주면 됩니다.

 

참 쉽죠?

 

파일은 올려두었어요.

 

https://github.com/outofcode-example/iOS-CustomView

 

outofcode-example/iOS-CustomView

CustomView의 예제 파일만 올려 보았습니다. Contribute to outofcode-example/iOS-CustomView development by creating an account on GitHub.

github.com

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함