(一)实现功能
单击按钮后可展开一个下拉列表,里面可以选择,选择后下拉列表收回;如果重新单击按钮后也可以收回;如果点击按钮列表区外面的时候也可以收回
(二)实现思路
1.首先定义一个UIButton 作为主按钮,一个UIView作为展开列表视图。
2.再定义几个UIButton,作为展开的表象,用 addSubview:childrenButton,将子按钮添加到列表视图。
3.将UIView设为隐藏。
4.再定义一个透明的按钮,充满整个屏幕,加入到父视窗,并设为隐藏
5.为主按钮设置一个bool值,用于判断当前列表是否已展开。
6.在透明按钮的点击事件中,将列表视图设为透明,同时更改当前状态为未展开
7.如果当前列表未展开:在主按钮的点击事件中,将UIView设为不隐藏(这样感觉就是按了按钮后弹出的view),将透明按钮也设为不隐藏(注意层级关系:列表view应该在透明按钮的上一层)这样在view内点击事件由子button获取,view外的点击事件由透明按钮获取
如果当前列表展开:将view设为隐藏,将透明按钮设为隐藏即可
(三)实现代码
static NSString *temStrOrd;//序号的字符串 static UIView *listView; static UIButton *bgBtn; static BOOL isShow=false; UIButton *btnAll; @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CGRect rect = [[UIScreen mainScreen] bounds]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(100, 100, 120, 50); [btn setTitle:@"点我展开" forState:UIControlStateNormal]; btn.backgroundColor = [UIColor blueColor]; [btn addTarget:self action:@selector(onBtnClicked) forControlEvents:UIControlEventAllTouchEvents]; [self.view addSubview:btn]; listView = [[UIView alloc] initWithFrame:CGRectMake(100, 152, 120, 100)]; [listView setBackgroundColor:[UIColor greenColor]]; listView.hidden = YES; [self.view addSubview:listView]; UIButton *childBtn1=[[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(100, 160, 110, 40)]; [childBtn1 setTitle:@"子按钮1" forState:UIControlStateNormal]; [childBtn1 setBackgroundColor:[UIColor whiteColor]]; [childBtn1 addTarget:self action:@selector(onChildBtn1Clicked) forControlEvents:UIControlEventAllTouchEvents]; [listView addSubview:childBtn1]; UIButton *childBtn2=[[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(100, 210, 110, 40)]; [childBtn2 setTitle:@"子按钮2" forState:UIControlStateNormal]; [childBtn2 setBackgroundColor:[UIColor whiteColor]]; [childBtn2 addTarget:self action:@selector(onChildBtn2Clicked) forControlEvents:UIControlEventAllTouchEvents]; [listView addSubview:childBtn2]; UIButton *bgBtn =[[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(0, 0, rect.size.width , rect.size.height)]; bgBtn.hidden = YES; [bgBtn addTarget:self action:@selector(onBGBtnClicked) forControlEvents:UIControlEventAllTouchEvents]; [self.view addSubview:bgBtn]; } -(void)onBtnClicked { if (isShow) { listView.hidden = YES; isShow=false; bgBtn.hidden =YES; }else{ listView.hidden=NO; isShow = true; bgBtn.hidden =NO; } } -(void)onBGBtnClicked { listView.hidden = YES; bgBtn.hidden = YES; isShow = false; NSLog(@"点击了背景透明按钮"); } -(void)onChildBtn1Clicked { NSLog(@"点击了子按钮1"); } -(void)onChildBtn2Clicked { NSLog(@"点击了子按钮2"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
(四)注意事项
1.层叠结构
如但