먼저 View파일을 생성해보자.
File
-> New File
-> Cocoa Touch Class
UIView
를 상속받는 클래스로 생성해주자.
import UIKit
class CustomView: UIView {
let testLabel: UILabel = {
let label = UILabel()
label.text = "View와 Controller 나누기"
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
testLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(testLabel)
testLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
testLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
initializer
를 작성해주고, 간단하게 UILabel
을 추가해주었다.
이제 ViewController
로 이동해보자
import UIKit
class ViewController: UIViewController {
var customView: CustomView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
customView = CustomView(frame: self.view.frame)
self.view = customView
}
}
만들어둔 CustomView를 받아오고 ViewController의 view를 교체해주면 끝!
view
랑 controller
를 분리해서 쓰다보니 UIButton
addTarget
부분을 어떻게 해야할 지 모르겠어서 찾아봤다.
import UIKit
class CustomView: UIView {
let testButton: UIButton = {
let btn = UIButton()
btn.setTitle("Click!", for: .normal)
btn.backgroundColor = .systemBlue
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
testButton.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(testButton)
testButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
testButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
일단 CustomView
에 UIButton
을 추가해줬다.
import UIKit
class ViewController: UIViewController {
var customView: CustomView!
override func viewDidLoad() {
super.viewDidLoad()
customView.testButton.addTarget(self, action: #selector(buttonTapped) , for: .touchUpInside)
}
override func loadView() {
super.loadView()
customView = CustomView(frame: self.view.frame)
self.view = customView
}
@objc
func buttonTapped() {
print("tapped!")
}
}
다음 ViewController
에서 customView
에 접근해서 addTarget
해주면 된다.