【问题标题】:Xcode ios Background image on multiple views多个视图上的 Xcode ios 背景图像
【发布时间】:2014-02-25 23:20:31
【问题描述】:

我最近发现了如何对开关进行编程以及如何从 1 个视图更改背景。

我的问题是在改变开关的值时如何改变多个视图(UIImage)的背景。

例如:这是一个偏好页面,当我切换偏好页面的背景时会发生变化,因此切换工作。

现在我希望名为“viewcontroller”的第一个视图的背景 (UIImage) 更改为与我的首选项页面的背景相同的背景。

【问题讨论】:

  • 你可以创建一个全局可用的变量(可以是一个单例或 - 不太干净 - 应用程序委托的公共属性),它保存背景图像,每个视图(控制器)都会在瞬间刷新它的背景在它变得可见之前(出现)
  • 你能给我一个代码示例吗???我在 Xcode 中还不是很好......
  • 好的。如果您想要更详细的答案,您可以将用于设置背景的代码添加到您的问题中。

标签: ios xcode background uiimage views


【解决方案1】:

在我看来,可能有很多不同的方法可以实现这一点。我要做的是将图像名称字符串保存到 [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 ...//

也许你必须根据实际使用情况做一些改变。但希望这能给你一些提示。

【讨论】:

    【解决方案2】:

    一种可能的解决方案是创建一个应用程序委托的公共属性来保存您的背景图像。

    @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)并使您的所有视图控制器成为此类的子类。

    注意 A:通常会(而不是 appDelegate 的属性)使用包含所有设置的单例类。这可能被认为是一种不好的(快速而肮脏的)做法。 More...

    注意 B:要保存最后选择的背景的名称,您可以使用 NSUserDefaults。这超出了这个问题的范围,并且有很多示例代码可用......

    【讨论】:

    • 感谢您的回复,我会尝试一下
    • 那行不通。如果我实施您的代码,我会收到错误消息Initializing 'AppDelegate *__strong' with an expression of incompatible type 'id<UIApplicationDelegate> _Nullable'
    【解决方案3】:

    是否可以将我保存在 Xcode 中的图像传递给下一个视图控制器?或者给它一个数字并将该数字传递给下一个视图控制器?比如switchone开启时,NSNumber = 1,传给下一个view,然后if (NSNumber == 1) than display "backgroundone.jpg"???

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 2019-08-18
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2016-09-09
      相关资源
      最近更新 更多