andehlu andehlu - 14 days ago 14
Swift Question

Adding Subclasses to UIView in Swift

I am unable to add a subclass to my parent UIView class. I am trying to build a BOOK class and have various UIView and UIImageView classes to build the covers and the pages. I get an error when adding the subclass to SELF. Would love some insight. PS - total 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)

Answer

The issue is that you can't call methods on self in the initializer until there is a self to call them on. There is no established value for self until you have called the superclass initializer. In other words, how does a subclass of UIView know how to "addSubview" when it has not yet been initialized as a UIView yet?

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()