[英]Adding Subclasses to UIView in Swift
I am unable to add a subclass to my parent UIView class. 我无法向我的父UIView类添加子类。 I am trying to build a BOOK class and have various UIView and UIImageView classes to build the covers and the pages. 我正在尝试构建一个BOOK类,并具有各种UIView和UIImageView类来构建封面和页面。 I get an error when adding the subclass to SELF. 将子类添加到SELF时出现错误。 Would love some insight. 希望有一些见识。 PS - total swift noob 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()
is a method on UIView
. addSubview()
是UIView
上的方法。 UIView
is your view's superclass. UIView
是视图的超类。 You cannot call methods on a superclass until it has been fully initialized. 在完全初始化超类之前,您不能在其上调用方法。
To fix this, call super.init(frame:)
earlier in your own init()
function (before you call addSubview()
). 要解决此问题,请在自己的init()
函数中(调用addSubview()
之前init()
先调用super.init(frame:)
。
The issue is that you can't call methods on self
in the initializer until there is a self
to call them on. 问题是,在没有self
可以调用它们的情况下,您无法在初始化器中对其self
调用方法。 There is no established value for self
until you have called the superclass initializer. 在调用超类初始化程序之前, self
没有确定的值。 In other words, how does a subclass of UIView know how to "addSubview" when it has not yet been initialized as a UIView yet? 换句话说,当尚未被初始化为UIView时,UIView的子类如何知道如何“ addSubview”?
So, in your code example, just move the line: 因此,在您的代码示例中,只需移动以下行:
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
to be before any time you call self.addSubview()
任何时候调用self.addSubview()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.