I have a game that when the button is pressed it goes to random position over the view controller. The only problem is that sometimes the button is positioned over my timer label. Are there any ways I could put a layer system in places so that timer label is always above the button. Here are two pictures describing the problem.
Here is my code:(the random generator is in action function pressSoccerBall).
import UIKit
class lthreeViewController: UIViewController {
@IBOutlet var timeRunnig: UILabel!
@IBOutlet var score1: UILabel!
@IBOutlet var score2: UILabel!
@IBOutlet var soccerFigure: UIButton!
public var LebelText: String?
public var LebelText2: String?
public var LebelText3: String?
var level = 0
var timer: Timer?
var isRunning: Bool {
get {
return timer != nil
}}
var counter = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if isRunning {
return
}
refreshTimer()
score1.text = LebelText
score2.text = LebelText2
timeRunnig.text = String(format: "%.1f", counter)
}
@IBAction func pressSoccerBall(_ sender: Any) {
level += 1
soccerFigure.isHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
if let `self` = self {
self.soccerFigure.isHidden = false
// Find the button's width and height
let buttonWidth = self.soccerFigure.frame.width
let buttonHeight = self.soccerFigure.frame.height
// Find the width and height of the enclosing view
let viewWidth = self.soccerFigure.superview!.bounds.width
let viewHeight = self.soccerFigure.superview!.bounds.height
// Compute width and height of the area to contain the button's center
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
// Generate a random x and y offset
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
// Offset the button's center by the random offsets.
self.soccerFigure.center.x = xoffset + buttonWidth / 2
self.soccerFigure.center.y = yoffset + buttonHeight / 2
}}
}
func refreshTimer() {
if let timer: Timer = timer {
timer.invalidate()
}
timer = Timer.scheduledTimer(timeInterval: 0.1 ,target: self,selector: #selector(updateTimer),userInfo: nil, repeats: true)
}
func updateTimer() {
counter += 0.1
timeRunnig.text = String(format: "%.1f", counter)
if counter < 14.9 && level == 7 {
if let nextc = self.storyboard?.instantiateViewController(withIdentifier: "lfourViewController") as? lfourViewController {
nextc.LebelText3 = timeRunnig.text
nextc.LebelText2 = score2.text
nextc.LebelText = score1.text
self.present(nextc, animated: true, completion: nil)
timer?.invalidate()
}}
else if counter >= 15{
let next = self.storyboard?.instantiateViewController(withIdentifier: "loseViewController") as? loseViewController
self.present(next!, animated: true, completion: nil)
timer?.invalidate()
}}
}