Search code examples
iosswiftcocoa-touchuikit

Swift Extension to get coordinate position of the right side of a frame


I am laying my UI elements programmatically so i frequently need to know other views frame sides current position to lay another UI elements based on those positions, i found myself repeating this code more times than i would like to:

var mybutton = UIButton(frame: CGRectMake(10,10,20,20))

var myOtherButton = UIButton(frame: CGRectMake(mybutton.frame.origin.x + mybutton.frame.width, mybutton.frame.origin.y + mybutton.frame.height, 20, 20))

Basically i add origin and frame.width, i would appreciate some clues about an extension to get this value typing less code.


Solution

  • Try like this:

    extension UIButton {
        var subFrame: CGRect {
           .init(x: frame.origin.x + frame.width, y: frame.origin.y + frame.height, width: frame.width, height: frame.height)
        }
    }
    
    let mybutton = UIButton(frame: CGRectMake(10,10,20,20))
    print(mybutton.subFrame)   // {x 30 y 30 w 20 h 20}
    
    let myOtherButton = UIButton(frame: mybutton.subFrame)