更改方向更改背景失败

时间:2015-01-10 07:01:00

标签: ios swift ios8 ios8.1

我有两张图片bg-landbg-port用于不同的方向。我想在chnaging方向上改变图像。但是,图像不会改变。当我在LandScape中加载模拟器时,bg-land工作正常但不适用于旋转。代码:

   override func viewDidLoad() {
        super.viewDidLoad()
        loadBackground()  
    }

    func loadBackground(){

        if(UIApplication.sharedApplication().statusBarOrientation.isPortrait){
            var bgImage      = UIImage(named: "bg-port")
            var background   = UIImageView(frame: self.view.bounds);
            background.image = bgImage
            self.view.addSubview(background)
            self.view.sendSubviewToBack(background)
            println(bgImage)
        } else {
            var bgImage      = UIImage(named: "bg-land")
            var background   = UIImageView(frame: self.view.bounds);
            background.image = bgImage
            self.view.addSubview(background)
            self.view.sendSubviewToBack(background)
            println(bgImage)
        }


    }

    override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
        loadBackground()
    }

2 个答案:

答案 0 :(得分:2)

这段代码对我来说很好,试试这个:

   override func viewDidLoad() {
   super.viewDidLoad()
   self.loadBackground()
}
func loadBackground(){

    if(UIApplication.sharedApplication().statusBarOrientation.isPortrait){
        let imageName = "Texture.jpg"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)

        imageView.frame = self.view.bounds
        view.addSubview(imageView)
    } else {
        let imageName = "AppIcon.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)

        imageView.frame = self.view.bounds
        view.addSubview(imageView)
    }


}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
    loadBackground()
}

不要忘记从此代码更改图像名称。

可能会对你有帮助。

答案 1 :(得分:1)

它没有改变,因为您将新添加的UIImageView发送到之前创建的UIImageView的背面。而不是这样做,在类中为UIImageView创建一个成员变量。 (将其命名为background

func loadBackground()
{
   if self.background == nil
   {
      self.background = UIImageView()
      self.view.addSubview(self.background)
      self.view.sendSubviewToBack(self.background)
   }

   if(UIApplication.sharedApplication().statusBarOrientation.isPortrait)
   {
        var bgImage           = UIImage(named: "bg-port")
        self.background.frame = self.view.bounds;
        self.background.image = bgImage
   }
   else
   {
        var bgImage           = UIImage(named: "bg-land")
        self.background.frame = self.view.bounds;
        background.image      = bgImage
   }
}

但最好在界面中添加UIImageView插座并使用代码加载图像,而不是在运行时创建一个。我更喜欢这是一个很好的方法。