custom view 만들기
- UIView 를 상속하는 customView 클래스 만들기
기본 형태는 아래처럼.
import UIKit
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: coder)
commonInit()
}
// 변수초기화하면서 클래스를 초기화하는 convenience init()
convenience init(progress:[Double], frame:CGRect) {
self.init(frame:frame)
self.progress = CGFloat(progress[0])
self.progressIn = CGFloat(progress[1])
self.progressOut = CGFloat(progress[2])
commonInit()
}
private func commonInit() {
}
override func draw(_ rect: CGRect) {
// Drawing code
}
}
xib 기반으로 만들 경우
customView.swift UIView 상속 customView.xib
xib 에서 File’s owner 를 customView로 잡아주고, xib 내의 컨트롤러들을 @IBOutlet 으로 잡아주는데, 최상위 view를 contentView로 가져오는 것을 기억할 것.
class DateProgressView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var img:UIImageView!
@IBOutlet weak var btnDate: UIButton!
@IBOutlet weak var progress: UIProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
contentView.fixInView(self)
self.layer.cornerRadius = 10
self.layer.masksToBounds = true
//self.isOpaque = false
contentView.backgroundColor = UIColor.yellow
btnDate.setTitle("", for: .normal)
progress.progress = 0.0
}
@IBAction func buttonTapped(_ sender: Any) {
//print("date tapped")
delegate?.dateTapped(sender)
}
}