将UIView作为SubView添加到自定义类,UIView,Swift的子类

时间:2015-01-26 22:52:26

标签: class swift uiview subclass addsubview

我遇到以下问题。 我有一个自定义类,UIView的子类 在其中,我尝试添加一个新的UIView,但它不让我。

class myCustomViewClass: UIView {

let smallerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

        self.view.addSubview(smallerView) // Error with this !

}

我尝试了不同的东西。 我知道如果我从UIViewController继承,我可以使它工作,但我不是真的想这样做。

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:-1)

class myCustomViewClass: UIView {

   let smallerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

    override func drawRect(rect: CGRect) {
       self.addSubview(smallerView) 
    }

}