问题
I have an UIImageView (img) on the container2View as an IBOutlet. How can I change the img.image and refresh the view from other container (containerView)?
We have to use delegation
mainController
class mainController: UIViewController, containerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case "container":
var view = segue.destinationViewController as containerController
view.delegate = self
break
default: break
}
}
func change(name: String) {
println(name) //prints the name
container2Controller().img.image = UIImage(named: "name") //not seems to work
}
}
containerController
protocol containerDelegate {
func change(name: String)
}
class containerController: UIViewController {
var delegate: containerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func click() {
delegate?.change("hi")
}
}
container2Controller
class container2Controller: UIViewController, containerDelegate {
@IBOutlet var img: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func change(name: String){
self.img.image = UIImage(named: name)
}
}
回答1:
You could handle this by using delegation. Let's say container2
has a button that when pressed should initiate an update to container4
.
In Container2
, declare a delegate protocol like:
@protocol Container2Delegate
- (void) actionDidOccurInContainer2: (Container2) container2;
@end
and add a property to Container2
class:
@property (weak, nonantomic) id<Container2Delegate> delegate;
Then implement the delegate method in the superContainer, and set Container2
s delegate to be the superContainer (in prepareForSegue
if you're using storyboards).
In the method implementation, you can update Container4
:
- (void) actionDidOccurInContainer2: (Container2) container2 {
container4.imageView.image = <your image>
}
In container2
you'll have something like:
- (IBAction)doSomething: (id) sender
{
[self.delegate actionDidOccurInContainer2: self];
}
来源:https://stackoverflow.com/questions/27377011/delegation-change-variables-from-different-viewscontrollers