将自定义UIButton添加到subView

时间:2012-03-20 05:29:14

标签: iphone ios uibutton subview

我有子视图,它是通过触摸主视图中的UI按钮启动的。 弹出子视图后,它会显示一个标签,其中包含我提供的信息。这一切都有效。我只需要一个UI按钮显示,然后我可以将其设置为关闭子视图并返回主视图。我已经搜遍了所有,但没有找到任何帮助。

以下是我的.m文件中的代码:

////Button that Displays Subview with Its Label and Button
- (IBAction)showInfo:(id)sender
/////UI Subview

{UIView *mySubview = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 480)];

[self.view addSubview:mySubview];
mySubview.backgroundColor = [UIColor blackColor];
mySubview.alpha = .7f;

//////Label in SubView

{UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 50)];
label.text = @"Here is info";
label.textColor = [UIColor whiteColor];
label.backgroundColor= [UIColor clearColor];

[self.view addSubview:label];


////Button in Subview

//create the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"button-info-x.png"]     forState:UIControlStateNormal];

//set the position of the button
button.frame = CGRectMake(120, 252, 68, 68);


//add the button to the view
[self.view addSubview:button];

现在我只需要向UIButton添加一个动作来解除Subview?

3 个答案:

答案 0 :(得分:5)

首先获取subView的IBOutlet并将其添加到主View。

 IBOutlet UIView *subView;

然后,将UIButton添加到SubView,如下所示:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

//set the position of the button
button.frame = CGRectMake(0, 0, 100, 30);

//set the button's title
[button setTitle:@"Click Me!" forState:UIControlStateNormal];

[btnMenu addTarget:self action:@selector(your MethodName:) forControlEvents:UIControlEventTouchUpInside];

//add the button to the view
[subView addSubview:button];

然后,

-(IBAction)your MethodName:(id)sender {


}

在上面的方法中从主视图中删除SubView。

答案 1 :(得分:0)

如果您只是想为UIButton而不是标题设置图像,那么您正在寻找- (void)setImage:(UIImage *)image forState:(UIControlState)state方法。

您应该查看UIButton reference了解详情。

答案 2 :(得分:0)

将目标添加到自定义按钮

{

.....

    [button addTarget:self action:@selector(your dismiss:) forControlEvents:UIControlEventTouchUpInside];

.......

}
-(IBAction)your dismiss:(id)sender 
{

   // write the dismissal code here

}