-1

Is there any way to combine two CGRect? I want to add "y: 65.0" to an existing CGRect and can't seem to find any way to do it. Sounds like a simple task to me but seems impossible to do in Xcode since "+=" isn't allowed between CGRect's.

EDIT: Tried using offsetBy and adding them using the following code. When adding the CGRect's i get the error message: No '+' candidates produce the expected contextual result type 'CGRect'

    var fromRect:CGRect = self.tableView.rectForRow(at: indexPath)
    let addRect = CGRect(x: 0.0, y: 65.0, width: 0.0, height: 0.0)

    //fromRect.offsetBy(dx: 0, dy: 65.0)
    fromRect = fromRect + addRect

2 Answers2

0

Or maybe you could just implement an operator yourself :

func +(left: CGRect, right: CGRect) -> CGRect {
    let origin = CGPoint(x: left.origin.x + right.origin.x, y: left.origin.y + right.origin.y)
    let size = CGSize(width: left.size.width + right.size.width, height: left.size.height + right.size.height)
    return CGRect(origin: origin, size: size)
}

func +=(left: inout CGRect, right: CGRect) {
    left = left + right
}

but there is a simpler solution to that problem without using operators: Just do this: (I'm not sure about this part because it seems that you want to do something more complex ?)

rect.origin.y += 65 
Stormsyders
  • 285
  • 2
  • 11
0

If you are wanting to literally add an offset to a rect's position, as in your example of adding y:65, you can use rect.offsetBy(dx: 0, dy: 64).

charmingToad
  • 1,597
  • 11
  • 18
  • Doesn't work for me for some reason. Code i have tried: var fromRect:CGRect = self.tableView.rectForRow(at: indexPath) let addRect = CGRect(x: 0.0, y: 65.0, width: 0.0, height: 0.0) //fromRect.offsetBy(dx: 0, dy: 65.0) romRect = fromRect + addRect When i'm trying to use the last line of code i get the error "No '+' candidates produce teh extended contextual result type 'CGRect' – stackoverflowlivesmatter Nov 05 '16 at 22:37
  • I'm not sure what you are doing in your last line. If you are trying to offset a rect by 65 y, then let newRect = fromRect.offsetBy(dx: 0, dy: 65.0). You can't use the "+" operator on rects. The offsetBy function can be used to add to the X or Y position of a rect. – charmingToad Nov 07 '16 at 17:16