复杂的 &如果循环混乱,返回和访问类。 Objective-C
我有一个包含多个子视图的视图。我需要找到具有特定 UIImage 的特定 UIImageView。
这是我用来循环的代码:
BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
if ([[subview class] isSubclassOfClass: [UIImageView class]]){
// I need to detect the subview's image property to see if it matches.
}
}
我已经尝试过
if(subview.image == [UIImage imageNamed:image]){
}
但我被告知图像不是结构的一部分,这是可以理解的,因为所有子视图本质上都是 UIView 类型。如何仅定位 UIImageViews,然后检查它们的图像属性?
关于“标签”答案,我尝试的代码是:
BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
if ([subview isKindOfClass:[UIImageView class]]){
if ((UIView *)subview.tag){
NSLog(@"FOUND");
}
}
}
I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.
Here is the code I'm using to loop through:
BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
if ([[subview class] isSubclassOfClass: [UIImageView class]]){
// I need to detect the subview's image property to see if it matches.
}
}
I've tried
if(subview.image == [UIImage imageNamed:image]){
}
But I'm getting told that image isn't part of the structure, which is understandable as all the subviews are essentially of UIView type. How do I target only the UIImageViews and then check their image property?
Regarding the 'tag' answer, the code I tried was:
BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
if ([subview isKindOfClass:[UIImageView class]]){
if ((UIView *)subview.tag){
NSLog(@"FOUND");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[UIImage imageNamed:image] 将返回该图像的新实例,因此它永远不会相等。我建议标记您的所有子视图。因此,当您创建图像视图时,请分配一个唯一的标签(这可能只是一个自动递增的数字)。然后您可以根据标签检测感兴趣的内容。
还可以使用 isKindOfClass 检查类类型。
希望这有帮助。
[UIImage imageNamed:image] will return a new instance of that image so it will NEVER be equal. I'd suggest tagging all of your subviews. So when you create the image views, assign a unique tag (this could just be an auto incrementing number). Then you can detect of interest based on the tag.
Also use isKindOfClass to check the class type.
Hope this helps.
您是否尝试过使用类型转换?
更新:
您还可以尝试更改迭代逻辑:
for (UIView *subview in drawGallery.subviews) {
如果您必须找到带有标签的单个视图,请尝试
UIImageView *imageViewISearchFor = [drawGallery viewWithTag:uniqueIDAssignedToImage];
Did you try to use type conversion?
UPDATE:
You can also try to change iteration logic:
for (UIView *subview in drawGallery.subviews) {
If you have to find a single view with tag, try
UIImageView *imageViewISearchFor = [drawGallery viewWithTag:uniqueIDAssignedToImage];