Convert CGSize to CGFloat and use that to size a RoundRectButton

ElasticThoughts picture ElasticThoughts · Feb 1, 2012 · Viewed 15.8k times · Source

I'm trying to find the physical pixel size of a string of text. I then want to use this size to set the length of a roundRectButton. The method I'm using to get the length however returns a CGSize. How do I convert that to a CGFloat? Alternatively perhaps someone can suggest a totally different way to accomplish this.

This is the code I have currently:

// Note: tagAsString is a string of Tag names (Example "tag1, tag2, tag3")
// Note: Code to set this is not relevant to the question.

// get length of tagsAsString.
CGSize tagStringLength = [tagsAsString sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:13.0] forWidth:100.0 lineBreakMode:UILineBreakModeTailTruncation];

// size button to fit length of string
// Note: spotTags is a roundRectButton
cell.spotTags.frame = CGRectMake(96, 33, tagStringLength, 25);

// set the title of the roundRectButton to the tag string
[cell.spotTags setTitle:tagsAsString forState:UIControlStateNormal];

As you can see above I'm using the CGRectMake method which takes 4 arguments as CGFloat. I am however passing in a CGSize which is causing a run-time error.

Answer

Carl Norum picture Carl Norum · Feb 1, 2012

CGSize is a structure:

struct CGSize {
   CGFloat width;
   CGFloat height;
};
typedef struct CGSize CGSize;

Just use tagStringLength.width to get the number you care about.

And I'm pretty sure you should be getting a compile-time error, not a run-time error.