2015-01-03 35 views
0

我想在我的遊戲中無限滾動背景。我的應用程序崩潰,當我嘗試做這樣的:如何在swift中實現無限滾動背景

@IBAction func levelClicked(sender: AnyObject) { 
    let screenSize: CGRect = UIScreen.mainScreen().bounds 
    let screenHeight = screenSize.height 
    let imageName = "levelBackground" 
    let image = UIImage(named: imageName) 
    imageView = UIImageView(image: image!) 

    imageView.frame = CGRect (x: 0, y: 0, width: 5500, height: screenHeight) 
    view.addSubview(imageView) 

    timer = NSTimer.scheduledTimerWithTimeInterval(0.5, 
             target: self, 
             selector: Selector("moveBackground"), 
             userInfo: nil, 
             repeats: true) 
} 

func moveBackground() { 
    imageView.frame = CGRect(x: imageView.frame.origin.x - 5, 
          y: imageView.origin.y, 
         width: 5500, 
         height: UIScreen.mainScreen().bounds.height) 
} 

這裏是我的崩潰日誌:

2015-01-03 15:57:56.579 zombieSurvival[3395:708290] -[zombieSurvival.firstBuildingViewController moveBackground]: unrecognized selector sent to instance 0x15e7e150

2015-01-03 15:57:56.585 zombieSurvival[3395:708290] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[zombieSurvival.firstBuildingViewController moveBackground]: unrecognized selector sent to instance 0x15e7e150'

*** First throw call stack:

(0x29dad5f7 0x374e7c77 0x29db2abd 0x29db0999 0x29ce1b88 0x2aac1a45 0x29d73f07 0x29d73a89 0x29d71cf3 0x29cbeb31 0x29cbe943 0x31077051 0x2d2b46f1 0xccc04 0xccc40 0x37a83aaf)

libc++abi.dylib: terminating with uncaught exception of type NSException

+0

你有某種crashlog嗎? –

+0

打印出zombieSurvival.firstBuildingViewController.class(s​​omewhere)和self.class(在'timer ='之前)。 –

+0

這只是給了我更多的錯誤。 – Wiem

回答

1

我不是迅速的專家,但似乎這是不工作了:

您在levelClicked中聲明moveBackground作爲函數,但是在您的計時器中,您引用的是self作爲目標。該類本身沒有方法moveBackground。它只在你的功能levelClicked內部可見。

嘗試將整個moveBackground移出levelClicked

爲了使moveBackground工作,我想你必須給imageView屬性。

@IBAction func levelClicked(sender: AnyObject) { 
    let screenSize: CGRect = UIScreen.mainScreen().bounds 
    let screenHeight = screenSize.height 
    let imageName = "levelBackground" 
    let image = UIImage(named: imageName) 
    self.imageView = UIImageView(image: image!) 

    self.imageView.frame = CGRect (x: 0, y: 0, width: 5500, height: screenHeight) 
    view.addSubview(self.imageView) 

    timer = NSTimer.scheduledTimerWithTimeInterval(0.5, 
             target: self, 
             selector: Selector("moveBackground"), 
             userInfo: nil, 
             repeats: true) 
} 

func moveBackground() { 
    self.imageView.frame = CGRect(x: self.imageView.frame.origin.x - 5, 
            y: self.imageView.origin.y, 
           width: 5500, 
          height: UIScreen.mainScreen().bounds.height) 
} 
+0

該應用程序仍然崩潰,但這次它給了我這個錯誤:'EXC_BAD_ACCESS(code = 1,address = 0x0)' – Wiem

+0

你可以更新代碼段嗎? –

+0

我更新了上面的代碼。 – Wiem