ios - 具有相同背景的多个 ViewController

标签 ios swift

如何在多个 View Controller 中实现一张静态背景图像?

使用 self.view.backgroundColor = UIColor(patternImage: UIImage(named: "file.png")) 背景会在屏幕切换时随着 UIViewController 一起移动。

是否可以将图像放在 View Controller 下的单独层上?

最佳答案

解决方案一

创建一个名为 MyBackground 的类:

class MyBackground {
   class func addBackgroundImage() {
        UIGraphicsBeginImageContext(self.view.frame.size)
        UIImage(named: "file")?.drawInRect(self.view.bounds)

        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        view.backgroundColor = UIColor(patternImage: image)
    }
}

如果您想在 AViewController 中调用它,只需调用 MyBackground.addBackgroundImage()

方案二

创建一个名为 MyViewController 的 ViewController:

class MyViewController: UIViewController {
   override func viewDidLoad() {
   super.viewDidLoad()
   addBackgroundImage()
}

func addBackgroundImage() {
            UIGraphicsBeginImageContext(self.view.frame.size)
            UIImage(named: "file")?.drawInRect(self.view.bounds)

            let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()

            UIGraphicsEndImageContext()

            view.backgroundColor = UIColor(patternImage: image)
        }
}

如果您的 AViewController 想要设置此图像,只需这样做:

AViewController: MyViewController //AViewController is a subclass of MyViewController

例如:我有一个图片调用background,我将把它设置为我的ViewController的背景图片:

enter image description here

如果我像@startupthekid 所说的那样将它添加到一行中:

enter image description here

如果我按照我说的那样添加:

enter image description here

关于ios - 具有相同背景的多个 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759919/

相关文章:

ios - 如何从另一个 Controller 打开嵌入式 Segue Controller ?

ios - EZAudio 停止获取音频

objective-c - Realm swift 创建 objective-c 文件

ios - IPV6 快速可达性

ios - UITableViewCell 标签没有更新

ios - 如何将 IBOutlet 连接到自定义 UIView?

ios - 向 iOS 项目添加和访问二进制 blob 原始数据文件

json - 如何使用 swiftJson 和 Alamofire 解析 json 数据

ios - Swift:为什么闭包函数调用迟了

ios - 如何让tableview控件适合整个屏幕