ios - 在 Swift 中向 UIView 添加子类

标签 ios swift uiview swift-playground

我无法将子类添加到我的父 UIView 类。我正在尝试构建一个 BOOK 类并使用各种 UIView 和 UIImageView 类来构建封面和页面。将子类添加到 SELF 时出现错误。会喜欢一些见识。 PS - 完全 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)

最佳答案

问题是您不能在初始化程序中调用 self 上的方法,直到有一个 self 可以调用它们。在您调用父类(super class)初始值设定项之前,self 没有确定的值。也就是说,UIView的子类在还没有初始化为UIView的情况下,怎么知道如何“addSubview”呢?

因此,在您的代码示例中,只需移动以下行:

super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight))

在您调用 self.addSubview() 之前的任何时间

关于ios - 在 Swift 中向 UIView 添加子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821441/

相关文章:

ios - 展开/最小化 UITableView 自定义单元格

ios - UIButton 在 View Controller 上不起作用

swift - 在 Swift 中使用 iRareMedia iCloudDocumentSync

swift - 无法使用 Storyboard将窗口连接到 IBOutlet

iphone - 如何截取 View 的屏幕截图并通过电子邮件发送?

ios - 在 iOS 中水平滚动字符并在中心放大一个字符

ios - WatchKit WKInterfaceMovie fatal error : unexpectedly found nil while unwrapping an Optional value

ios - 使用两个 UICollectionView 在 UITableView 中显示不同的数据

ios - swift : Update UIView using multipeer connectivity

ios - 了解uiview和uiviewcontroller