I don't see why you would use static
, you want to set up the UI of a UIView
's instance, thus no need to have a static
class method.
In your ViewExample
:
import UIKit
class ViewExample: UIView {
func setupUI() {
let labelTitle: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello, world!"
return label
}()
self.backgroundColor = .white
self.addSubview(labelTitle)
NSLayoutConstraint.activate([
labelTitle.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 10),
labelTitle.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10),
labelTitle.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10),
])
}
override init(frame: CGRect){
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupUI()
}
}
In your ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = ViewExample(frame: (x: 0, y: 0, width: 200, height: 50)) //Change the frame according to where you want to position your view
self.addSubview(view)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…