Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is CGRectGetMidX/Y in Swift 3

Tags:

ios

swift3

IN Siwft 3, I could not find CGRectGetMidX and Y which I used to calclate position of nodes. Also I could not find CGPointMake. IN this case, how am I able to set nodes in the center of SKScene?

Thanks!

Update: I created a node and specified the position of it, by writing this way;

let node = SKSpriteNode()
node.position = CGPoint(x:self.frame.size.width/2, y:self.frame.size.height/2)
node.size = CGSize(width: 100, height: 100)
node.color = SKColor.red
self.addChild(node)

Why is it somewhere else like different place from the specified location? I firstly thought there was a change in Swift3 and the depresciation of CGPointMake caused this problem, but it does not seem like it is the cause. In this case, is the use of CGRect better? It is very helpful if you could write code that fixs this position issue. Again, thank you for your help.

like image 970
Ryohei Avatar asked Oct 14 '16 05:10

Ryohei


2 Answers

In Swift you shouldn't use those old style notations. Just use the constructors and properties:

let point = CGPoint(x: 1, y: 2)
let rect = CGRect(x: 1, y: 2, width: 3, height: 4)
let mx = rect.midX
like image 166
Sami Kuhmonen Avatar answered Nov 15 '22 19:11

Sami Kuhmonen


C global functions like CGRectGetMidX/Y, CGPointMake, etc. shouldn't be used in Swift (they're deprecated in Swift 2.2, removed in Swift 3).

Swift imports CGRect and CGPoint as native types, with initializers, instance methods, etc. They're much more natural to use, and they don't pollute the global name space as the C functions once did.

let point = CGPoint(x: 0, y: 0) //replacement of CGPointMake

let rect = CGRect(x: 0, y: 0, width: 5, height: 5) //replacement of CGRectMake

let midX = rect.midX //replacement of CGRectGetMidX
let midY = rect.midY //replacement of CGRectGetMidY

Their respect API reference is linked above. You might also find the CoreGraphics API reference handy too.

like image 40
Alexander Avatar answered Nov 15 '22 19:11

Alexander