我最近发现了如何编程开关以及如何从1个视图中更改背景。
我的问题是如何在更改开关值时更改多个视图(UIImage)的背景。
例如:这是一个首选项页面,当我切换首选项页面的背景时,更改以便交换机正常工作。
现在我希望我的第一个名为“ viewcontroller ”的视图的背景(UIImage)更改为与我的首选项页面背景相同的背景。
答案 0 :(得分:0)
可能的解决方案之一是创建包含背景图像的应用程序委托的公共属性。
@property (strong) UIImage *globalBackground;
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
中,您应将其初始化为某个默认图片或上次保存的图片。
self.globalBackground = [UIImage imageNamed:@"defaultBackground"];
假设您的appDelegate头文件是MyAppDelegate.h。您应该在使用此默认背景图像机制的所有类中导入它。或者只是将其添加到Prefix.pch
文件中。
在您的设置视图控制器中,您将设置:
//your background setting handler
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.globalBackground = ... //however you get the selected image
//and here you set the background image of settings view controller
然后在每个视图控件viewWillAppear:
中,您以类似的方式设置其背景:
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//then you use appDelegate.globalBackground the same way you are doing it now
如果您有很多视图控制器,您可能需要考虑创建一个实现此机制的UIViewController
子类(可能称之为UIViewControllerWithBackground
)并使该类的所有视图控制器都成为子类。
注意答:一个人(而不是appDelegate的属性)通常使用包含所有设置的单例类。它可能被认为是一种糟糕(快速和肮脏)的做法。 More...
注意B:要保存上次选择的背景的名称,您可以使用NSUserDefaults
。这超出了这个问题的范围,并且有很多可用的示例代码...
答案 1 :(得分:0)
是否可以将我保存在Xcode中的图像传递给下一个viewcontroller?或者给它一个数字并将该数字传递给下一个viewcontroller?例如,当switchone打开时,NSNumber = 1,将其传递给下一个视图,然后if(NSNumber == 1)而不是显示“backgroundone.jpg”???
答案 2 :(得分:0)
在我看来,可能有很多不同的方法来实现这一目标。我要做的是将图像名称字符串保存到 [NSUserDefaults standardUserDefaults] 。
例如当开关值改变时,你调用
[[NSUserDefaults standardUserDefaults] setObject:@"BackgroundImageName" forKey:@"BackgroundImageOne.jpg"];
[[NSUserDefaults standardUserDefaults]synchronize];
当您设置背景时,您可以
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
UIImage *bgImage;
if ([userDefault objectForKey:@"BackgroundImageName"])
bgImage = [UIImage imageNamed:[userDefault objectForKey:@"BackgroundImageName"]];
else
bgImage = [UIImage imageNamed:@"DEFAULT_NAME"];
//... Set the bgImage to your background image view ...//
也许您必须根据实际使用情况进行一些更改。但希望这会给你一些提示。