[英]Adding Subclasses to UIView in Swift
我無法向我的父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)
addSubview()
是UIView
上的方法。 UIView
是視圖的超類。 在完全初始化超類之前,您不能在其上調用方法。
要解決此問題,請在自己的init()
函數中(調用addSubview()
之前init()
先調用super.init(frame:)
。
問題是,在沒有self
可以調用它們的情況下,您無法在初始化器中對其self
調用方法。 在調用超類初始化程序之前, self
沒有確定的值。 換句話說,當尚未被初始化為UIView時,UIView的子類如何知道如何“ addSubview”?
因此,在您的代碼示例中,只需移動以下行:
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
任何時候調用self.addSubview()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.