When I implemented CustomView
in code, my understanding of the init
method was ambiguous, so I will post it as a reminder.
【Xcode】Version 12.0.1 【Swift】Version 5.3
CustomView.swift
import UIKit
class CustomView: UIView {
var imageView: UIImageView!
//Detailed explanation ①
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
//Detailed explanation ②
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup(){
let iWidth: CGFloat = 200
let iHeight: CGFloat = 200
let posX: CGFloat = (self.frame.width - iWidth)/2
let posY: CGFloat = (self.frame.height - iHeight)/2
imageView = UIImageView(frame: CGRect(x: posX, y: posY, width: iWidth, height: iHeight))
imageView.image = UIImage(named: "hoge")
self.addSubview(imageView)
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let customView = CustomView()
customView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
self.view.addSubview(customView)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required
) may or may not be implemented as a subclass, but it is necessary to add override
when initializing.required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required
) must be implemented in subclasses.init? (coder aDecoder: NSCoder)
is defined in the NSCoding
protocol, which is implemented in the UIView
class, which means that it must also be implemented in a subclass.Recommended Posts