[英]Set Image On Another View's UIImageView
我正在嘗試創建一種“設置”頁面,我很難切換原始視圖的背景圖像。 到目前為止,代碼是:
-(IBAction)switchBackground:(id)sender {
ViewController *mainView = [[ViewController alloc] initWithNibName:nil bundle:nil];
mainView.displayedImage.image = [UIImage imageNamed:@"image.png"];;
}
也許我可以得到一些指示?
謝謝,所有。
每次調用switchBackground
方法時都要創建一個新的mainView
對象。 您必須更改現有對象的背景才能看到更改發生。
從您的代碼中很難說出switchBackground
方法的位置。 ViewController
?
如果它位於視圖控制器中,那么您所要做的就是:
self.displayedImage.image = [UIImage imageNamed:@"image.png"];
編輯
根據你的評論。
如果要從B類更改A類對象的圖像,可以通過兩種不同的方式完成:
1.通過參考一個對象
這是設置初始化程序,在創建時獲取指向現有mainView的指針
@property(nonatomic,assign)ViewController *mainView;
- (id)initWithMainViewController:(ViewController*)vc {
self = [super init];
if (self) {
self.mainView = vc;
}
return self;
}
-(IBAction)switchBackground:(id)sender {
mainView.displayedImage.image = [UIImage imageNamed:@"image.png"];
}
2.通過NSNotificationCenter發布本地通知。
-(IBAction)switchBackground:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName: @"changeImage" object: [UIImage imageNamed:@"image.png"]];
}
現在在你的ViewController中聽取通知並做出反應
在ViewController的init方法中
- (id)initWithMainViewController:(ViewController*)vc {
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeImage:) name:@"changeImage" object:nil];
}
return self;
}
-(void)changeImage:(NSNotification*)notification{
self.displayedImage.image = (UIImage*) notification.object;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.