2014-11-03 58 views
-1

所以每當我有這樣的:‘?UIImage的’Swift Xcode 6.1打破了我的代碼|操作數錯誤

let result = SKScrollingNode(color: UIColor.clearColor(), size:CGSizeMake(CGFloat(containerWidth), image.size.height)); 

我得到一個編譯錯誤的image.size.height,告訴我」沒有一個名爲「大小」,儘管它確實

任何想法成員這意味着什麼,以及如何解決它

感謝

整個代碼片段:!

class func scrollingNode(imageNamed: String, containerWidth: CGFloat) -> SKScrollingNode { 
    let image = UIImage(named: imageNamed); 

    let result = SKScrollingNode(color: UIColor.clearColor(), size: CGSizeMake(CGFloat(containerWidth), image.size.height)); 
    result.scrollingSpeed = 1.0; 

    var total:CGFloat = 0.0; 
    while(total < CGFloat(containerWidth) + image.size.width!) { 
     let child = SKSpriteNode(imageNamed: imageNamed); 
     child.anchorPoint = CGPointZero; 
     child.position = CGPointMake(total, 0); 
     result.addChild(child); 
     total+=child.size.width; 
    } 
    return result; 
+2

'UIImage'有'size'。 'UIImage?'不。 – matt 2014-11-03 15:36:52

+0

仍然無效:UIImage.size.height。獲取相同的錯誤,所以這不是問題 – Sarah 2014-11-03 15:39:06

+0

看看這個答案:http://stackoverflow.com/questions/26582035/in-xcode-6-1-uiimage-does-not-have-a-member- named-size-error – 2014-11-03 15:44:50

回答

4

在這行:

let image = UIImage(named: imageNamed) 

image是一個可選的,UIImage?

在這條線的錯誤:

let result = SKScrollingNode(color: UIColor.clearColor(), size: CGSizeMake(CGFloat(containerWidth), image.size.height)); 

可以縮小到這段代碼:

CGSizeMake(CGFloat(containerWidth), image.size.height) 

CGSizeMake要求2個CGFloat參數,但第二一個是可選的,因爲image是可選的:

  • if if image不是nil,image.size.height計算結果爲CGFloat的
  • 如果image是零,image.size.height計算結果爲無

爲了避免這種情況,你有兩個選擇:

  1. 使image非可選使用強制解包

    let image = UIImage(named: imageNamed)! 
    

    但我不推薦使用它,因爲如果UIImage創建失敗,應用程序將崩潰。

  2. 使用另購的結合:

    let image = UIImage(named: imageNamed); 
    if let image = image {  
        let result = SKScrollingNode(color: UIColor.clearColor(), size: CGSizeMake(CGFloat(containerWidth), image.size.height)); 
        // ... rest of the code here 
    } 
    

    這是一個更好的辦法來解開可選的,因爲如果它是零,在if語句的代碼將被跳過,不會出現運行錯誤。