第一次加载第二个视图控制器时,我得到一个闪烁(可能是视图控制器未完全加载)。我尝试通过segue进行预设,并在加载前将其设置在自定义初始值设定项中。我创建的影响是为每个视图控制器保持相同的背景。请注意,这仅在首次转换到视图控制器时发生。它不会发生在第一个segue之后。
非常感谢帮助。我在下面提供了适用的代码。
First View Controller:
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, UIScrollViewDelegate
{
// Background Image
var backgroundImage: UIImageView!
var backgroundImages: [String] = ["canyon.jpeg","channel.jpeg","glacier.jpeg","northernlights.jpeg", "jungle"]
var currentBackground = 0
init(_ coder: NSCoder? = nil)
{
// Logic Goes Here
if let coder = coder
{
super.init(coder: coder)!
} else
{
super.init(nibName: nil, bundle: nil)
}
}
required convenience init(coder: NSCoder)
{
self.init(coder)
}
override func viewDidLoad()
{
setUpView()
super.viewDidLoad()
}
func setUpView()
{
backgroundImage = UIImageView(frame: CGRect( x: 0 , y: 0, width: ScreenWidth, height: ScreenHeight))
backgroundImage.image = UIImage(named: backgroundImages[currentBackground])
backgroundImage.alpha = 1
let playButtonPercent:CGFloat = 0.75
playButton = UIButton(frame: CGRect(x: (ScreenWidth * 0.5) - (ScreenWidth * playButtonPercent / 2), y: (ScreenHeight * (3 / 4)) - (ScreenHeight * (15/480)), width: (ScreenWidth * playButtonPercent), height: ScreenHeight * (30/480)))
playButton.setTitle("PLAY", for: UIControlState())
playButton.addTarget(self, action: #selector(self.playRelease), for: .touchUpInside)
self.view.addSubview(backgroundImage)
self.view.addSubview(playButton)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if (segue.identifier == "Play")
{
if let nextViewController = (segue.destination as? GameListViewController)
{
nextViewController.currentBackground = currentBackground
nextViewController.backgroundImage.image = UIImage(named: self.backgroundImages[currentBackground])
}
}
}
func playRelease()
{
// Segue
performSegue(withIdentifier: "Play", sender: self)
}
}
查看控制器2:
class GameListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
let backgroundImages = ["canyon.jpeg","channel.jpeg","glacier.jpeg","northernlights.jpeg", "jungle"]
var currentBackground = 0
var backgroundImage: UIImageView!
override func viewDidLoad()
{
backgroundImage = UIImageView(frame: CGRect( x: 0 , y: 0, width: ScreenWidth, height: ScreenHeight))
super.viewDidLoad()
setUpView()
}
}
func setUpView()
{
backgroundImage.image = UIImage(named: backgroundImages[currentBackground])
backgroundImage.alpha = 1
self.view.addSubview(backgroundImage)
view.sendSubview(toBack: backgroundImage)
}
}