for循环创建多个按钮

  • (void)viewDidLoad {
    [super viewDidLoad];

    float x = 60;
    float y = 100;
    float w = 30;
    float h = 30;

    NSArray *btnTitles = [NSArray arrayWithObjects:@"button1",@"button2",@"button3",@"button4",@"button5", nil];

    for (num = 0; num<5; num++) {
    _btn = [UIButton buttonWithType:UIButtonTypeCustom];
    NSLog(@"%@",_btn);
    [_btn setFrame:CGRectMake(w+ num *x, y, w, h)];
    _btn.tag = num * 1000;

      NSDictionary * attributes =@{NSFontAttributeName:[UIFont fontWithName:@"Palatino-Roman" size:15],NSForegroundColorAttributeName:[UIColor redColor]};
      NSDictionary * attributesSelect =@{NSFontAttributeName:[UIFont fontWithName:@"Palatino-Roman" size:15],NSForegroundColorAttributeName:[UIColor blueColor]};
      //使用了富文本
      NSAttributedString *buttonTitleString =[[NSAttributedString alloc]initWithString:btnTitles[num] attributes:attributes];
      NSAttributedString *buttonTitleStringSelect=[[NSAttributedString alloc]initWithString:btnTitles[num] attributes:attributesSelect];
      
      [_btn setAttributedTitle:buttonTitleString forState:UIControlStateNormal];
      [_btn setAttributedTitle:buttonTitleStringSelect forState:UIControlStateDisabled];
     
      [_btn setTitle:[btnTitles objectAtIndex:num] forState:UIControlStateNormal];
      
      [_btn addTarget:self action:@selector(btn_click:) forControlEvents:UIControlEventTouchUpInside];
      [self.view addSubview:_btn];
    

    }

}

  • (void)btn_click:(UIButton )btn
    {
    _index = btn.tag;
    //在self.view.subviews 遍历view视图
    for(UIView * subView in self.view.subviews){
    //给[UIButton class] 做匹配
    if([subView isKindOfClass:[UIButton class]]){
    UIButton * subBtn = (UIButton
    )subView;
    if(subBtn.tag == btn.tag){
    [subBtn setEnabled:NO];

          }else{
              [subBtn setEnabled:YES];
              
          }
      }
    

    }
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容