繁体   English   中英

在Swift中将子类添加到UIView

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM