【问题标题】:Adding Subclasses to UIView in Swift在 Swift 中向 UIView 添加子类
【发布时间】:2016-11-26 18:06:38
【问题描述】:

我无法向我的父 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)

【问题讨论】:

  • 错误说明了什么?我认为 Xcode 在这里很清楚。
  • self 未初始化移动 super.init(frame: CGRect(x: 0, y: 0, width: bookwidth, height: bookheight)) 到 init 的第一行

标签: ios swift uiview swift-playground


【解决方案1】:

问题是你不能在初始化器中调用self 上的方法,直到有self 来调用它们。在调用超类初始化程序之前,self 没有确定的值。也就是说,UIView 的子类在还没有被初始化为 UIView 的情况下,怎么知道如何“addSubview”呢?

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

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

在您致电self.addSubview()之前任何时候

【讨论】:

    【解决方案2】:

    addSubview()UIView 上的一个方法。 UIView 是视图的超类。在完全初始化之前,您不能调用超类的方法。

    要解决此问题,请在您自己的 init() 函数中调用 super.init(frame:)(在调用 addSubview() 之前)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多