美文网首页
for循环创建多个按钮

for循环创建多个按钮

作者: 欲速则不达 | 来源:发表于2016-04-24 18:26 被阅读622次
  • (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];
              
          }
      }
    

    }
    }

相关文章

网友评论

      本文标题:for循环创建多个按钮

      本文链接:https://www.haomeiwen.com/subject/squfrttx.html