委托-从不同的视图更改变量 [英] Delegation - Change variables from different viewsControllers
问题描述
我在container2View上有一个UIImageView(img)作为IBOutlet。如何更改img.image并从其他容器(containerView)刷新视图?
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)?
我们必须使用委托
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)
}
}
推荐答案
您可以使用 < a href = https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html rel = nofollow>授权 。假设 container2
有一个按钮,当按下该按钮时,应启动对 container4
的更新。
You could handle this by using delegation. Let's say container2
has a button that when pressed should initiate an update to container4
.
在 Container2
中,声明一个委托协议,例如:
In Container2
, declare a delegate protocol like:
@protocol Container2Delegate
- (void) actionDidOccurInContainer2: (Container2) container2;
@end
并向 Container2 $添加属性c $ c>类:
@property (weak, nonantomic) id<Container2Delegate> delegate;
然后在 super Container中实现委托方法,并设置 Container2
委托为 super Container(如果使用情节提要,则在 prepareForSegue
中)。
Then implement the delegate method in the superContainer, and set Container2
s delegate to be the superContainer (in prepareForSegue
if you're using storyboards).
在方法实现中,您可以更新 Container4
:
In the method implementation, you can update Container4
:
- (void) actionDidOccurInContainer2: (Container2) container2 {
container4.imageView.image = <your image>
}
在 container2
中会有类似的内容:
- (IBAction)doSomething: (id) sender
{
[self.delegate actionDidOccurInContainer2: self];
}
这篇关于委托-从不同的视图更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!