【问题标题】:How can I add the same background image to all views in my ios app using swift?如何使用 swift 将相同的背景图像添加到我的 ios 应用程序中的所有视图?
【发布时间】:2018-06-21 11:00:04
【问题描述】:

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

现在,当我进行过渡时,新视图的背景也会“过渡”到我之前的视图,即使它的背景相同。我希望能够只设置内容过渡,而不是背景,这是一样的。

【问题讨论】:

  • 您应该能够通过继承 UIWindow 并覆盖 drawRect 来绘制图像来实现这一点。然后将 UIColor.clearColor 设置为所有视图的背景色。

标签: ios xcode swift


【解决方案1】:

您应该能够通过以下方式实现:

  1. 继承 UIWindow 并覆盖 drawRect 以绘制图像;有关子类化的详细信息 UIWindow here
  2. 然后使用UIAppearance 控制应用程序中其余视图的背景颜色(应将其设置为clearColor);有关此here 的详细信息,但我认为您需要对控制器使用的视图进行子类化,以处理已接受答案中的注释

基本实现可能如下所示:

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 中:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = WallpaperWindow()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2019-05-27
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多