Swift 3中的动态对象创建

时间:2016-12-17 19:49:12

标签: ios swift swift3

我是一个快速的菜鸟。我正在尝试构建动态对象。在我的例子中,我试图从我的BOOK类创建一个PAGE类的实例。我想我不知道如何动态创建它们/命名它们或引用它们以供以后使用。我明白我不能创建动态名称...我猜我把它们放入棕褐色阵列?任何帮助或意见的赞赏。

//page class
class pageview : UIView {

    var page: UIView!

    init () {

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

        page = UIView(frame: CGRect(x: bookposx, y: bookposy, width: bookwidth, height: bookheight))
        page.backgroundColor = UIColor.blue
        book.addSubview(page)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


//book class
class bookview : UIView {

    var cover: UIView!
    var backcover: UIView!
    var page: UIImageView!

    init (numberofpages: Int) {

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

        //pages
        for i in 0 ..< numberofpages {

            //PROBLEM HERE
            let page (i) = pageview()
            self.addSubview(page (i))

        }


    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


//add book
let book = bookview(numberofpages: 3)
container.addSubview(book)

1 个答案:

答案 0 :(得分:0)

我不知道我是否正确地解决了你的问题。但请查看:

class bookview : UIView {
var cover: UIView!
var backcover: UIView!
var pages: [pageview] = []

init (numberofpages: Int) {
    super.init(frame: CGRect(x: 0, y: 0, width: 400, height: 400))

    //pages
    for _ in 0 ..< numberofpages {
        let page = pageview()
        pages.append(page)
        self.addSubview(page)
    }
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
} }