以编程方式访问UIViewController子类中的UIView子类的成员

时间:2016-10-04 17:36:13

标签: swift uiview types uiviewcontroller subclass

我想将所有子视图属性和我的子视图设置代码放在UIView子类中,并使用loadView()将其加载到我的UIViewController子类中。然后访问UIView子类成员,而不是一直强制转换UIViewController的view属性。

这是我的UIView子类AwesomeClass

class AwesomeView: UIView {
    lazy var testView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.red
        self.addSubview(view)
        return view
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        testView.frame = CGRect(x: 10
            , y: 10
            , width: self.bounds.size.width - 20
            , height: 100)
    }
}

我的UIViewController子类AwesomeViewController

class AwesomeViewController: UIViewController {
    override func loadView() {
        let view = AwesomeView()
        self.view = view
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

我可以这样做:

var subclassedView:AwesomeView {
    get {
        return self.view as! AwesomeView
    }
}

subclassedView.testView.backgroundColor = UIColor.blue

但有没有办法直接使用testView中的self.view致电AwesomeViewController

修改 我正在寻找的是Covariant return type在swift中。

1 个答案:

答案 0 :(得分:0)

你可以这样:

AwesomeViewController

中实例化AwesomeView的实例
class AwesomeView: UIView {

var exampleColorVariable:UIColor?
//here you instantiate your view controller
var awesomeViewController = AwesomeViewController()

lazy var testView:UIView = {
    let view = UIView()
    view.backgroundColor = UIColor.red
    self.addSubview(view)
    return view
}()
override init(frame: CGRect) {
    super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
    super.layoutSubviews()
    testView.frame = CGRect(x: 10
        , y: 10
        , width: self.bounds.size.width - 20
        , height: 100)
  }
}

然后您可以访问AwesomeView中的任何方法更改您的代码

 class AwesomeViewController: UIViewController {

   lazy var awesomeView: AwesomeView = {
    let view = AwesomeView()
    view.awesomeViewController = self
    return view
   }()

   func setupView() {
    view.addSubview(awesomeView)
     // your constraints here 
   }

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    setupView()
    // NOW YOU CAN ACCESS ANY METHOD IN YOUR VIEW awesomeView.yourFunction()
    // or you access that variable 
    awesomeView.exampleColorVariable = .red // you can now omit UIColor in swift3
  }
}