我正在用drawRect实现一个UIView子类:我如何绘制一个按钮?

时间:2011-05-22 21:23:17

标签: objective-c ios uiview uibutton drawrect

我有一个UIView子类,我正在为我的应用程序中常用的小视图做。我绘制视图的图像和文本没有问题,现在我必须在此视图中添加2个按钮。这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

任何视图都可以包含子视图,即使视图实现了drawRect:也是如此。子视图的内容始终覆盖超级视图的内容。 UIButton是一个视图。因此,只需将按钮添加为自定义视图的子视图。

答案 1 :(得分:0)

您可以像这样添加:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[button setTitle:@"Button title" forState:UIControlStateNormal]; //Set the title for regular state
[button addTarget:self 
       action:@selector(yourMethod:)
 forControlEvents:UIControlEventTouchDown];
button.frame = CGRectMake(40, 100, 160, 240); //make the frame
[view addSubview:button]; //add to current view

虽然已经有几个主题涉及这个主题,但请使用搜索栏。 :)

答案 2 :(得分:0)

//required ...
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"who am i?" forState:UIControlStateNormal];
[button setFrame:CGRectMake(20, 20, 200, 40)];
[button addTarget:self action:@selector(performAction) forControlEvents:UIControlEventTouchUpInside];

//optional properties..
[button setBackgroundColor:[UIColor greenColor]];
[button setImage:[UIImage imageNamed:@"someImg.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"green-hdr-bg.png"] forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];

[yourCustomView addSubview:button];



-(void)performAction
{
    //do you button click task here
}