-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"Sample.png"];
[self.view addSubview:imageView];
NSArray *subviews = [self.view subviews];
for(id element in subviews) {
if ([[element class] isKindOfClass:[UIImageView class]]) //check if the object is a UIImageView
{
NSLog(@"element is a UIImageView\n");
[element setCenter:CGPointMake(500., 500.)];
} else {
NSLog(@"element is NOT a UIImageView\n");
}
}
}
我期望输出为“元素是UIImageView,但实际上元素不是UIImageView。为什么?不是有其他子视图。只有一个。此外,运行时,图像显示为100,100 ,不是预期的500,500。
答案 0 :(得分:45)
你的支票错了。你应该在对象上调用isKindOfClass:
而不是在对象类上调用。
[element isKindOfClass:[UIImageView class]]
答案 1 :(得分:0)
请尝试以下代码。
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"Sample.png"];
[self.view addSubview:imageView];
NSArray *subviews = [self.view subviews];
for(UIView *view in subviews) {
if ([view isKindOfClass:[UIImageView class]]) //check if the object is a UIImageView
{
NSLog(@"element is a UIImageView\n");
[element setCenter:CGPointMake(500., 500.)];
} else {
NSLog(@"element is NOT a UIImageView\n");
}
}
}
您还可以按标记值检查子视图:
initially set imageView.tag=101; //anything you want
for(UIView *subview in [view subviews]) {
if(subview.tag== 101)/*your subview tag value here*/
{
NSLog(@"element is a UIImageView\n");
} else {
NSLog(@"element is NOT a UIImageView\n");
}
}