我想为所有视图控制器设置相同的背景图像。这是我尝试过的:
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg_name.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
但这只能通过在任何地方复制粘贴来实现。什么是更好的方法呢?
答案 0 :(得分:1)
如果您希望在所有视图控制器中拥有相同的背景图像,那么一个选项是创建自定义基础ViewController
类,并让所有其他类继承该类。例如 -
class BackgroundImageViewController: ViewController {
override func viewDidLoad(_animated: Bool) {
super.viewDidLoad(animated: animated)
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg_name.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
}
}
然后 -
class AnotherViewController: BackgroundImageViewController {
// Your normal view controller stuff
}
答案 1 :(得分:1)
您可以创建视图控制器类的扩展
extension UIViewController {
/// This function sets an image as the background of the view controller
///
/// - Parameters:
/// - imageName: name of image
/// - contentMode:
/// .scaleAspectFill
/// .scaleAspectFit
/// .scaleToFill
func setBackgroundImage(_ imageName: String, contentMode: UIViewContentMode) {
let backgroundImage = UIImageView(frame: self.view.bounds)
backgroundImage.image = UIImage(named: imageName)
backgroundImage.contentMode = contentMode
self.view.insertSubview(backgroundImage, at: 0)
}
}
在任何UIViewController类中的用法
override func viewDidLoad() {
super.viewDidLoad()
self.setBackgroundImage("name_image", contentMode: .scaleAspectFit)
}