如何使用swift将相同的背景图像添加到ios应用程序中的所有视图中? [英] How can I add the same background image to all views in my ios app using swift?

查看:49
本文介绍了如何使用swift将相同的背景图像添加到ios应用程序中的所有视图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将背景图像添加到适用于所有视图的ios应用程序中,而不必将此图像添加到每个视图中.是否可以将图像添加到UIWindow或其他内容?

I want to be able to add a background image to my ios app that applies for all views and not having to add this image to every single view. Is it possible to add an image to UIWindow or something?

现在,当我执行过渡时,即使背景相同,新视图的背景也会在我先前的视图上过渡".我希望只能设置内容过渡,而不是背景,这是相同的.

Now, when I do a transition, the background of the new view also "transitions" over my previous view even though its the same background. I want to be able to only se the content transition, and not the background, which is the same.

推荐答案

您应该可以通过以下方式实现此目标:

You should be able to achieve this by:

  1. 子类化UIWindow并重写 drawRect 来绘制图像; UIWindow 子类化的详细信息此处
  2. 然后使用 UIAppearance 控制应用程序中其余视图的背景色(您应将其设置为 clearColor );关于此此处的详细信息,尽管我认为您是将需要对控制器使用的视图进行子类化,以便处理接受的答案中的注释
  1. subclassing UIWindow and overriding drawRect to draw your image; details about subclassing UIWindow here
  2. and then by using UIAppearance to control the background colour for the rest of the views in your app (you should set it to clearColor); details about this here, though I think you'll need to subclass the views used by your controllers in order to cope with the note in the accepted answer

一个基本的实现可能看起来像这样:

A basic implementation could look like this:

class WallpaperWindow: UIWindow {

    var wallpaper: UIImage? = UIImage(named: "wallpaper") {
        didSet {
            // refresh if the image changed
            setNeedsDisplay()
        }
    }

    init() {
        super.init(frame: UIScreen.mainScreen().bounds)
        //clear the background color of all table views, so we can see the background
        UITableView.appearance().backgroundColor = UIColor.clearColor()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func drawRect(rect: CGRect) {
        // draw the wallper if set, otherwise default behaviour
        if let wallpaper = wallpaper {
            wallpaper.drawInRect(self.bounds);
        } else {
            super.drawRect(rect)
        }
    }
}

在AppDelegate中:

And in AppDelegate:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = WallpaperWindow()

这篇关于如何使用swift将相同的背景图像添加到ios应用程序中的所有视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆