swift - 如何从不在父/子关系中的另一个类修改对象的属性?

时间:2015-07-24 10:31:55

标签: swift class viewcontroller

我知道如何在父/子关系模式下修改对象的属性,但是,如果不是父/子关系,我真的无法做到,任何人都可以解决我的问题?

第一个viewController:

class ViewController: UIViewController {

var uview:UIView = UIView()

override func viewDidLoad() {
    super.viewDidLoad()

    uview.frame = CGRectMake(55, 175, 100, 100)
    uview.backgroundColor = UIColor.greenColor()
    self.view.addSubview(uview)

    var sec = second()
    self.view.addSubview(sec.view)

}
}

第二个viewController:

class second:UIViewController{

var button = UIButton()

var color = UIColor.blackColor()
override func viewDidLoad() {
    super.viewDidLoad()

    button.frame = CGRectMake(55, 55, 100, 100)
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: "press", forControlEvents:UIControlEvents.TouchUpInside)
    self.view.addSubview(button)

}

func press(){
    var first:ViewController = ViewController()
    first.uview.backgroundColor = UIColor.purpleColor()

}
}

1 个答案:

答案 0 :(得分:0)

你添加一个像this question这样的委托,或者你可以简单地将第二个视图控制器声明为第一个的实例属性:

class ViewController: UIViewController {
    var uview:UIView = UIView()
    var sec : second!

    override func viewDidLoad() {
        super.viewDidLoad()

        uview.frame = CGRectMake(55, 175, 100, 100)
        uview.backgroundColor = UIColor.greenColor()
        self.view.addSubview(uview)

        self.sec = second()
        self.view.addSubview(sec.view)
    }
}