NewGen

Create Custom UIView and Use in ViewController / 사용자 커스텀 뷰 (닙생성) 만들고 뷰컨트롤러에서 불러쓰기 본문

IOS

Create Custom UIView and Use in ViewController / 사용자 커스텀 뷰 (닙생성) 만들고 뷰컨트롤러에서 불러쓰기

Deep Learning 2020. 11. 24. 00:48

 

1. 아무거나 사용자 닙 하나 만듬. / Create custom uiview.xib

 

2. MyView.swift 를 아래와 같이 만들어줌. / Create MyView.swift and Type code below.....and focus on nib file name.

I had a wrong xib name... I wanted "MyView.xib", but wrote "MtView.xib"..

So, I faced crash app.....

import UIKit

 

class MyView: UIView {

    @IBOutlet var main_view: UIView!

    

    @IBOutlet weak var text_label: UILabel!

    override init(frame: CGRect) {

        super.init(frame: frame)

       

    }

    

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        

        customInit()

    }

    

   func customInit() {

        if let view = Bundle.main.loadNibNamed("MtView", owner: self, options: nil)?.first as? UIView {

            view.frame = self.bounds

            self.addSubview(view)

        }

    }

    /*

    // Only override draw() if you perform custom drawing.

    // An empty implementation adversely affects performance during animation.

    override func draw(_ rect: CGRect) {

        // Drawing code

    }

    */

 

}

 

3. 원하는 뷰 컨트로러에 붙임. / Add UIView and set constrains..

 

4. 뷰컨트롤러에서 저래 불러쓰믄 뎀 / Call MyView(custom view) as below...

import UIKit

 

class ViewController: UIViewController {

 

    @IBOutlet weak var my_view: MyView!

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view.

        

        print("viewDidLoad")

        //addCustomView()

    }

 

    /*

    func addCustomView() {

        if let customView = Bundle.main.loadNibNamed("MyView", owner: nil, options: nil)?.first as? UIView {

            customView.frame = self.view.bounds

            my_view.addSubview(customView)

        }

    }

    */

}

 

End.

Comments