从数组中获取CGRect
对于我的应用程序,我尝试将 CGRect 对象存储到 NSMutableArray 中。它加载良好并在日志语句中打印,但尝试从数组中获取 CGRect 会显示错误。这是一个代码片段:
CGRect lineRact = CGRectMake([[attributeDict objectForKey:@"x"] floatValue],
[[attributeDict objectForKey:@"y"] floatValue],
[[attributeDict objectForKey:@"width"] floatValue],
[[attributeDict objectForKey:@"height"] floatValue]);
[lineRactangle addObject:NSStringFromCGRect(lineRact)];
如何从数组中获取矩形?
For my application I am trying to store CGRect
objects into an NSMutableArray
. It is loading well and printing in the log statement, but trying to take the CGRect
s from the array shows an error. Here is a code snippet:
CGRect lineRact = CGRectMake([[attributeDict objectForKey:@"x"] floatValue],
[[attributeDict objectForKey:@"y"] floatValue],
[[attributeDict objectForKey:@"width"] floatValue],
[[attributeDict objectForKey:@"height"] floatValue]);
[lineRactangle addObject:NSStringFromCGRect(lineRact)];
How can I get the rects back from the array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
CGRect 是一个结构体,而不是一个对象,因此不能存储在 NSArrays 或 NSDictionaries 中。您可以将其转换为字符串,然后将该字符串转换回 CGRect,但最好的方法是通过 NSValue 封装它:
然后您可以将此 NSValue 对象存储在数组和字典中。要将其变回 CGRect,您需要执行以下操作:
A CGRect is a struct, not an object, and thus cannot be stored in NSArrays or NSDictionaries. You can turn it into a string and turn that string back into a CGRect, but the best way is to encapsulate it via an NSValue:
You can then store this NSValue object in arrays and dictionaries. To turn it back into a CGRect, you'd do:
使用
NSValue
包装CGRect
,从而将它们存储在NSArray
中。例如:
请参阅文档了解其他支撑结构。
Use
NSValue
to wrapCGRect
thus store them inNSArray
s.For example:
See documentation for the other supported structures.
事实上,我认为迄今为止的任何答案都没有真正解决阿杰提出的问题。简短的答案是:您需要为 CGRectMake 提供 intValue,而不是字典项的 floatValue。如果您需要对多个 CGRect 执行此操作,这里有一个建议的方法:
可能有一种更优雅的方法来完成此操作,但上面的代码确实有效。
Actually, I don't think any of the answers thus far really address the question ajay asked. The short answer is: You need to supply CGRectMake with the intValue, rather than the floatValue of the dictionary item. If you need to do this for several CGRects, here's a suggested method:
There may be a more elegant way to accomplish this, but the above code does work.
如果您的对象可以使用“.frame”设置,您可以使用:
或 对于多个对象:
If your object can be set with ".frame" you could use:
or for multiple objects:
CGRect 是一个结构体,您不能将其放入 NSArray 中。您只能向其中添加对象。
CGRect is a struct you cannot put it in an NSArray. You can only add objects to it.
或者更“极端”的东西...创建一个包含 CGRect 数组的数组
,其中“GridAA”、“GridAB”等对应于 UIViews
or something more 'extreme'... creating an array that holds arrays of CGRect(s)
where 'GridAA', 'GridAB' etc. correspond to UIViews