[英]View does not appear when made into its own custom view class
I'm making a simple view programatically in Swift and I have this first code that is working just fine: 我正在Swift中以编程方式制作一个简单的视图,并且我的第一个代码运行得很好:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
let card:UIView = UIView()
card.frame = CGRect(x: 38, y: 120, width: 300, height: 300)
card.backgroundColor = .white
card.layer.cornerRadius = 10
card.layer.shadowOpacity = 0.5
card.layer.shadowOffset = CGSize(width: 0, height: 10)
card.layer.shadowRadius = 10
view.addSubview(card)
}
}
This code make this view: 此代码使该视图:
But I want to reuse the card so I put it into a new class like a custom view, but the card now disappears: 但是我想重复使用卡,因此将其放入自定义视图之类的新类中,但卡现在消失了:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
let card = Card(frame: CGRect(x: 38, y: 120, width: 300, height: 300))
view.addSubview(card)
}
}
class Card:UIView {
var box:UIView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
func setupLayout(){
box.backgroundColor = .white
box.layer.cornerRadius = 10
box.layer.shadowOpacity = 0.5
box.layer.shadowOffset = CGSize(width: 0, height: 10)
box.layer.shadowRadius = 10
addSubview(box)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Do you know what is wrong with the second code? 您知道第二个代码有什么问题吗?
Your box
doesn't know where it should be drawn. 您的
box
不知道应该在哪里绘制。 Add in this one line, which gives it a frame (an origin & size): 在这一行中添加一个框架(原点和大小):
func setupLayout(){
box.backgroundColor = .white
box.layer.cornerRadius = 10
box.layer.shadowOpacity = 0.5
box.layer.shadowOffset = CGSize(width: 0, height: 10)
box.layer.shadowRadius = 10
// here's the line to add!
box.frame = self.frame.insetBy(dx: 10.0, dy: 10.0)
self.addSubview(box)
}
This is better: 这个更好:
func setupLayout(){
box.backgroundColor = .white
box.layer.cornerRadius = 10
box.layer.shadowOpacity = 0.5
box.layer.shadowOffset = CGSize(width: 0, height: 10)
box.layer.shadowRadius = 10
box.frame = self.frame
self.addSubview(box)
}
It automatically gets the frame from the initializer. 它会自动从初始化程序获取帧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.