我无法将子类添加到我的父UIView类。我正在尝试构建一个BOOK类,并拥有各种UIView和UIImageView类来构建封面和页面。将子类添加到 SELF 时出现错误。希望得到一些见解。PS - 总迅捷菜鸟
//book
class bookview : UIView {
var cover: UIView!
var backcover: UIView!
var page: UIImageView!
init (pages: Int) {
//backcover cover
backcover = UIView(frame: CGRect(x: 200, y: 200, width: bookwidth, height: bookheight))
backcover.backgroundColor = UIColor.blue
self.addSubview(backcover) //ERROR HERE
//pages
for i in 0 ..< pages {
page = UIImageView(frame: CGRect(x: bookwidth * i/10, y: bookheight * i/10, width: bookwidth, height: bookheight))
page.backgroundColor = UIColor.red
self.addSubview(page) //ERROR HERE
}
//front cover
cover = UIView(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
cover.backgroundColor = UIColor.blue
self.addSubview(cover) //ERROR HERE
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//add book
let book = bookview(pages: 3)
问题是,在有self
调用方法之前,您无法在初始值设定项中调用self
方法。 在调用超类初始值设定项之前,没有self
的既定值。 换句话说,UIView 的子类在尚未初始化为 UIView 时如何知道如何"添加Subview"?
因此,在您的代码示例中,只需移动该行:
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
在你打电话给self.addSubview()
的任何时候之前
addSubview()
是UIView
上的一种方法。UIView
是视图的超类。 在超类完全初始化之前,不能对超类调用方法。
若要解决此问题,请先在自己的init()
函数中调用super.init(frame:)
(在调用addSubview()
之前)。