How to Create a Cgsize in Swift

How to Create a CGSize in Swift?

Your first attempt won't work because C structs don't exist in Swift. You need:

let size = CGSize(width: 20, height: 30)

Or (before Swift 3 only, and even then, not preferred):

let size = CGSizeMake(20,30)

(Not MakeSize).

How do I create constants of type CGSize in header file in iOS?

For fixed height and width

  1. #define MAXSIZE CGSizeMake(320, 480)

For passing values, you can give the value MySizeType i.e defined as CGSize. But for Constant why do you want to pass values.


  1. typedef CGSize MySizeType;

EDIT

After few comments not to use Macros I am elaborating my answer over here.

Using MACROS the drawback is that your debugger cannot know the constant.

And also there more ways to create a constant depends on the scope of your constant you want,

  1. For internal class only

static CGSize const MAXSIZE = {320, 480};


  1. For outside class

In .h file

extern CGSize const MAXSIZE;

In .m file

CGSize const MAXSIZE = {320,480};

Aspect fit in cgsize programmatically in swift

You can solve this issue by put the code block into the viewDidAppear(_:). In this method, the size will be corrected.

@IBOutlet weak var header: UILabel!

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

header.adjustsFontSizeToFitWidth = true

let rectShape = CAShapeLayer()
rectShape.bounds = self.header.frame
rectShape.position = self.header.center
rectShape.path = UIBezierPath(roundedRect: self.header.bounds, byRoundingCorners: [.bottomLeft , .bottomRight], cornerRadii: CGSize(width:300, height: 200)).cgPath

self.header.layer.backgroundColor = UIColor.green.cgColor
//Here I'm masking the textView's layer with rectShape layer
self.header.layer.mask = rectShape
}

CGSize sizeWithAttributes in Swift

Just one line solution:

yourLabel.intrinsicContentSize.width for Objective-C / Swift

This will work even your label text have custom text spacing.

What is an alternative for CGSizeMake in Swift 3.0

Please use

CGSize(width: <CGFloat>, height: <CGFloat>)

How do I create a CGRect from a CGPoint and CGSize?

Two different options for Objective-C:

CGRect aRect = CGRectMake(aPoint.x, aPoint.y, aSize.width, aSize.height);

CGRect aRect = { aPoint, aSize };

Swift 3:

let aRect = CGRect(origin: aPoint, size: aSize)

How to define += extension functions on CGSize

You must also define the += operator. As an assignment operator, its left-hand-side parameter should be inout and it should return Void.

extension CGSize {
static func += (lhs: inout Self, rhs: Self) {
lhs.width += rhs.width
lhs.height += rhs.height
}
}

Or, taking advantage of your existing definition of +:

extension CGSize {
static func += (lhs: inout Self, rhs: Self) {
lhs = lhs + rhs
}
}


Related Topics



Leave a reply



Submit