【发布时间】:2011-05-22 21:23:16
【问题描述】:
我有一个 UIView 子类,我正在为整个应用程序中常用的小视图制作。我绘制视图的图像和文本没问题,现在我必须向该视图添加 2 个按钮。这样做的正确方法是什么?
【问题讨论】:
标签: objective-c ios uiview uibutton drawrect
我有一个 UIView 子类,我正在为整个应用程序中常用的小视图制作。我绘制视图的图像和文本没问题,现在我必须向该视图添加 2 个按钮。这样做的正确方法是什么?
【问题讨论】:
标签: objective-c ios uiview uibutton drawrect
任何视图都可以有子视图,即使视图实现了drawRect:。子视图的内容总是覆盖父视图的内容。 UIButton 是一个视图。因此,只需将按钮添加为自定义视图的子视图即可。
【讨论】:
你可以像这样简单地添加它:
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
虽然已经有几个主题讨论了这个主题,请使用搜索栏。 :)
【讨论】:
//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
}
【讨论】: