我在container2View上有一个UIImageView(img)作为IBOutlet。如何更改img.image并从其他容器(containerView)刷新视图?
我们必须使用委托
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)
}
}
答案 0 :(得分:1)
您可以使用 delegation 来解决此问题。我们假设container2
有一个按钮,按下该按钮时应启动对container4
的更新。
在Container2
中,声明一个委托协议,如:
@protocol Container2Delegate
- (void) actionDidOccurInContainer2: (Container2) container2;
@end
并向Container2
类添加属性:
@property (weak, nonantomic) id<Container2Delegate> delegate;
然后在 super 容器中实现委托方法,并将Container2
委托设置为 super 容器(prepareForSegue
如果你& #39;重新使用故事板。)
在方法实施中,您可以更新Container4
:
- (void) actionDidOccurInContainer2: (Container2) container2 {
container4.imageView.image = <your image>
}
在container2
中你会有类似的内容:
- (IBAction)doSomething: (id) sender
{
[self.delegate actionDidOccurInContainer2: self];
}