【问题标题】:Swift: timer resetting the viewSwift:计时器重置视图
【发布时间】:2023-03-31 12:12:01
【问题描述】:

所以我有一个使用NSTimer 每秒计数 1 的标签。我制作了一个应用程序,其中有一些动人的UIImages。然而,每次计时器计数到一个时,视图似乎都会重新加载,UIImages 会回到原来的位置。此外,UIImages 不是我将它们放置在情节提要中的位置(我将它们放置在视图之外,以便它们可以向内移动,但是当我启动应用程序时它只是在那里显示它们。它们移动但仅用于一个第二然后回到原来的位置)。相同的代码在 iPhone 上运行良好,但在 iPad 上无法运行。我认为这与约束有关,因为代码是相同的。这是计时器代码:

 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.
}

这是移动我的 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)
    }

我的限制:

开始和结束游戏的两个按钮(水平居中)。

四个UIImage(大小比例)

一个计时器(左上角),由于某种原因,它会在每次计数时重置视图。

【问题讨论】:

  • 我们应该如何帮助您获取有关您的代码的有限信息?
  • 您在哪里绘制/移动图像?您可以控制哪些自动布局约束?

标签: ipad swift timer constraints reload


【解决方案1】:

我遇到了完全相同的问题。我通过为每个可移动视图添加以下代码来解决它:

override func viewDidLoad() {
    super.viewDidLoad()
    self.imageView.translatesAutoresizingMaskIntoConstraints = true
    self.imageView2.translatesAutoresizingMaskIntoConstraints = true
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多