Question Asker Question Asker - 6 months ago 19
Objective-C Question

Using Objective-C macros to access UIView frame measurements in Swift

I have just started to shift from Obj-C to Swift in Xcode.

Is there no way to use macros from

any more? I understand that I can use
to define constants instead, but I am used to having this set of macros at the top of most of my programs, for example:

#define frameMinX CGRectGetMinX(self.frame)
#define frameMinY CGRectGetMinY(self.frame)
#define frameMidX CGRectGetMidX(self.frame)
#define frameMidY CGRectGetMidY(self.frame)
#define frameMaxX CGRectGetMaxX(self.frame)
#define frameMaxY CGRectGetMaxY(self.frame)

#define frameMin CGPointMake(frameMinX, frameMinY)
#define frameMid CGPointMake(frameMidX, frameMidY)
#define frameMax CGPointMake(frameMaxX, frameMaxY)


You cannot use the #defines in Swift, but these all seem to be computations on the frame of a UIView, so you can extend UIView to add them as computed properties:

extension UIView {
    var frameMinX: CGFloat { return CGRectGetMinX(self.frame) }
    var frameMinY: CGFloat { return CGRectGetMinY(self.frame) }
    var frameMidX: CGFloat { return CGRectGetMidX(self.frame) }
    var frameMidY: CGFloat { return CGRectGetMidY(self.frame) }
    var frameMaxX: CGFloat { return CGRectGetMaxX(self.frame) }
    var frameMaxY: CGFloat { return CGRectGetMaxY(self.frame) }
    var frameMin: CGPoint  { return CGPointMake(frameMinX, frameMinY) }
    var frameMid: CGPoint  { return CGPointMake(frameMidX, frameMidY) }
    var frameMax: CGPoint  { return CGPointMake(frameMaxX, frameMaxY) }

Usage Example:

Inside of any subclass of UIView, you can use the properties just as you would the macros:

class CustomView: UIView {
    func demoProperties() {

let view = CustomView(frame: CGRect(x: 50, y: 100, width: 200, height: 300))



(250.0, 400.0)