Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call CGRectDivide in Swift?

Tags:

ios

swift

I'm trying to call CGRectDivide and can't figure out the syntax in Swift. The language guide doesn't seem to be any help.

Here's the template:

CGRectDivide(rect: CGRect, slice: CMutablePointer<CGRect>, remainder: CMutablePointer<CGRect>, amount: CGFloat, edge: CGRectEdge)

My code:

var r = UIScreen.mainScreen().bounds
var mySlice: CGRect
var myRemainder: CGRect
CGRectDivide(rect: CGRect, slice: mySlice<CGRect>, remainder: myRemainder<CGRect>, amount: 44.0, edge: CGRectEdge.MaxYEdge)

That gives me an error: "Cannot specialize a non-generic definition"

I'm stumped. So much for Swift being a very readable language.

like image 341
pizzafilms Avatar asked Jun 08 '14 15:06

pizzafilms


2 Answers

If you Command-click on a CGRect symbol in your code, you'll be taken to the Swift declaration of struct CGRect. In its first extension you'll find a number of useful methods, including the following:

Swift 2:
func divide(atDistance: CGFloat, fromEdge: CGRectEdge) -> (slice: CGRect, remainder: CGRect)

Swift 3:
func divide(_ atDistance: CGFloat, fromEdge: CGRectEdge) -> (slice: CGRect, remainder: CGRect)

Which you could use like this:

import UIKit

let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
let (slice, remainder) = rect.divide(10.0, fromEdge: .MinXEdge) // Swift 3: .minXEdge
print("rect: \(rect)") // prints "rect: (0.0,0.0,100.0,100.0)"
print("slice: \(slice)") // prints "slice: (0.0,0.0,10.0,100.0)"
print("remainder: \(remainder)") // prints "remainder: (10.0,0.0,90.0,100.0)"
like image 54
Wolf McNally Avatar answered Nov 19 '22 16:11

Wolf McNally


Just sample, how you can try to do it:

let rect = CGRectMake(0, 0, 100, 100)
var sliceRect = CGRectZero
var remainderRect = CGRectZero
CGRectDivide (rect, &sliceRect, &remainderRect, 30.0, "CGRectEdge");

print(sliceRect)
print(remainderRect)

"CGRectEdge" should be replaced by:

enter image description here

like image 5
pkis Avatar answered Nov 19 '22 15:11

pkis