将CGSize转换为CGFloat并使用它来调整RoundRectButton的大小

Ela*_*hts 4 iphone objective-c string-length strlen sizewithfont

我正在尝试找到一串文本的物理像素大小.然后,我想使用此大小来设置roundRectButton的长度.然而,我用来获取长度的方法返回CGSize.如何将其转换为CGFloat?或者,也许有人可以建议一种完全不同的方式来实现这一点

这是我目前的代码:

// 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];
Run Code Online (Sandbox Code Playgroud)

正如您在上面所看到的,我正在使用CGRectMake方法,该方法将4个参数作为CGFloat.然而,我传入一个导致运行时错误的CGSize.

Car*_*rum 20

CGSize 是一个结构:

struct CGSize {
   CGFloat width;
   CGFloat height;
};
typedef struct CGSize CGSize;
Run Code Online (Sandbox Code Playgroud)

只是tagStringLength.width用来得到你关心的数字.

而且我很确定你应该得到一个编译时错误,而不是运行时错误.


zap*_*aph 5

CGSize是两个元素的结构:CGFloat宽度和CGFloat高度.

示例代码:

CGSize size;
CGFLoat width = size.width;
CGFLoat height = size.height;
Run Code Online (Sandbox Code Playgroud)