Objective c 添加子视图不需要';行不通

Objective c 添加子视图不需要';行不通,objective-c,xcode,Objective C,Xcode,当我按下一个按钮时,它应该加上一个胡子,但它没有为什么你要告诉我必须把它的父母带到前面来?试试这个: [self.view将子视图带到前面:必须] 确保名为mustache.png的图像存在。。 这个对我有用 - (IBAction)add { UIImageView *must = [UIImageView alloc]; [must setImage:[UIImage imageNamed:@"themustache.png"]]; must.center =

当我按下一个按钮时,它应该加上一个胡子,但它没有

为什么你要告诉我必须把它的父母带到前面来?试试这个:
[self.view将子视图带到前面:必须]

确保名为mustache.png的图像存在。。 这个对我有用

- (IBAction)add {

    UIImageView *must = [UIImageView alloc];
    [must setImage:[UIImage imageNamed:@"themustache.png"]];  
    must.center = CGPointMake(0, 0);

    [self.view addSubview:must];
    [must bringSubviewToFront:self.view];
}

请尝试此代码,它将帮助您。
首先,设置UIImageView的框架,并将该imageview添加到视图中,它将正常工作

-(IBAction)add {  
UIImageView *must=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,50, 50)];  
must.image=[UIImage imageNamed:@"themustache.png"];  
[self.view addSubview:must];  
}

确保按钮连接到Interface Builder中的正确操作。还可以将其放入add方法NSLog(@“Pressed”);中;。如果已连接,则每次按下按钮时都会看到控制台中显示的Pressed(按下)消息。

请尝试此操作,并让我知道它是否工作

-(IBAction)add  
{
    UIImageView *must = [UIImageView alloc];
    must.frame = CGRectMake(10.0, 50.0, 262.0, 34.0);
    must.backgroundColor = [UIColor clearColor];
    [must setImage:[UIImage imageNamed:@"themustache.png"]];
    [self.view bringSubviewToFront:must];

}
或者这个,

- (IBAction)add {
UIImage *mustImage = [UIImage imageNamed:@"themustache.png"];
UIImageView *must = [[UIImageView alloc] initWithImage:mustImage];
[self.view addSubview:must];  
[mustImage release];
[must release];
}  
如果从AppDelegate.m调用函数,请尝试使用
window
而不是
self.view

以上两项都必须适用。

@user894725:检查png,如果它不在资源文件夹中。它的图像是否在资源文件夹中?检查。希望这有帮助。并在函数中添加NSLog(),看看它是否被调用(请参阅登录控制台)。尝试一下。是的,它被调用。您是否从MainAppDelegate调用此函数?否,我不是从uiviewcontroller子类调用是的,控制台执行NSLog,我可以看到,所以这个按钮起作用了。我唯一能建议的是删除must.center=CGPointMake(0,0);。这可能是将其定位在屏幕外。@ms83:
must.center=CGPointMake(0,0)可以。它将使图像的中心正好位于屏幕的左上角。就这样。因此,用户将只能看到图像的第四部分(右下角)。@user885074:无需调用
[self.view bringsubview tofront:must]
。不要静止不动,这可能是我的图像,即使它是同一个名称
- (IBAction)add {
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);
UIImageView *must = [[UIImageView alloc] initWithFrame:myImageRect];
[must setImage:[UIImage imageNamed:@"themustache.png"]];
[self.view addSubview:must];  
[must release];
}
- (IBAction)add {

    UIImageView *must = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];

    [must setImage:[UIImage imageNamed:@"themustache.png"] forState:UIControlStateNormal];

    [self.view addSubview:must];

    [must release];
}