在 Swift 中向 UIView 添加子类
Adding Subclasses to UIView in Swift
我无法将子class 添加到我的父 UIView class。我正在尝试制作一本书 class 并使用各种 UIView 和 UIImageView class 来制作封面和页面。将 subclass 添加到 SELF 时出现错误。会喜欢一些见识。 PS - 总计 swift 菜鸟
//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()
函数中更早地调用 super.init(frame:)
(在调用 addSubview()
之前)。
问题是您无法在初始化程序中调用 self
上的方法,直到有 self
可以调用它们。在您调用超类初始值设定项之前,self
没有确定的值。换句话说,UIView的子类在还没有初始化为UIView的情况下如何知道如何"addSubview"?
因此,在您的代码示例中,只需移动以下行:
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
在您致电 self.addSubview()
之前
我无法将子class 添加到我的父 UIView class。我正在尝试制作一本书 class 并使用各种 UIView 和 UIImageView class 来制作封面和页面。将 subclass 添加到 SELF 时出现错误。会喜欢一些见识。 PS - 总计 swift 菜鸟
//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()
函数中更早地调用 super.init(frame:)
(在调用 addSubview()
之前)。
问题是您无法在初始化程序中调用 self
上的方法,直到有 self
可以调用它们。在您调用超类初始值设定项之前,self
没有确定的值。换句话说,UIView的子类在还没有初始化为UIView的情况下如何知道如何"addSubview"?
因此,在您的代码示例中,只需移动以下行:
super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))
在您致电 self.addSubview()