问题
So I have a label that counts 1 every second using an NSTimer
. I made an app that has a few moving UIImage
s. However every time the timer counts one up, the view seemingly reloads and the UIImage
s go back to their original positions. Furthermore, the UIImage
s are not where I had placed them in the storyboard (I placed them outside the view so they could move inwards, but when I start the app it just shows them right there already. They move but only for one second then go back to their original positions). Same code works fine on the iPhone but doesn't work on an iPad. I think it has something to do with the constraints because the code is the same. Here's the timer code:
func counting() {
timerCount = timerCount + 1
timerLabel.text = "\(timerCount)"
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("counting"), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a override nib.
}
Here's the code for moving my UIImages:
func MoveWalls() {
FirstTimer = NSTimer.scheduledTimerWithTimeInterval(0.07, target: self, selector: Selector("FirstMoving"), userInfo: nil, repeats: true)
SecondTimer = NSTimer.scheduledTimerWithTimeInterval(0.007, target: self, selector:
Selector("SecondMoving"), userInfo: nil, repeats:true)
ThirdTimer = NSTimer.scheduledTimerWithTimeInterval(0.006, target: self, selector:
Selector("ThirdMoving"), userInfo: nil, repeats:true)
FourthTimer = NSTimer.scheduledTimerWithTimeInterval(0.005, target: self, selector:
Selector("FourthMoving"), userInfo: nil, repeats:true)
}
func FirstMoving() {
First.center = CGPointMake(First.center.x + 1, First.center.y)
}
func SecondMoving() {
Second.center = CGPointMake(Second.center.x - 1, Second.center.y)
}
func ThirdMoving() {
ThirdMoving.center = CGPointMake(Third.center.x, Third.center.y + 1)
}
func FourthMoving() {
Fourth.center = CGPointMake(Fourth.center.x, Fourth.center.y 1)
}
My constraints:
Two buttons that start and end the game (Centered horizontally).
The four UIImages (size ratio)
A timer (Top left) which for some reason resets the view with each count.
回答1:
I had the exact same problem. I solved it by adding this code for each of the moveable views:
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.translatesAutoresizingMaskIntoConstraints = true
self.imageView2.translatesAutoresizingMaskIntoConstraints = true
}
来源:https://stackoverflow.com/questions/29961767/swift-timer-resetting-the-view