我无法将子类添加到我的父 UIView 类。我正在尝试构建一个 BOOK 类并使用各种 UIView 和 UIImageView 类来构建封面和页面。将子类添加到 SELF 时出现错误。会喜欢一些见识。 PS - 完全 swift noob
//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
可以调用它们。在您调用父类(super class)初始值设定项之前,self
没有确定的值。也就是说,UIView的子类在还没有初始化为UIView的情况下,怎么知道如何“addSubview”呢?
因此,在您的代码示例中,只需移动以下行:
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
在您调用 self.addSubview()
之前的任何时间
关于ios - 在 Swift 中向 UIView 添加子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821441/