IOS界面开发使用viewWithTag:(int)findTag方法获取界面元素

今天在开发OS界面的时候,遇到通过界面UIview viewWithTag:(int)findTag选择器定位界面元素的问题,以下把在界面中给元素打Tag,以及通过选择器查找界面元素的代码贴出来,供以后使用:

界面元素打tag

 //事件监听的问题
        CGRect btn2Frame = CGRectMake(100.0, 150.0, 60.0, 44.0);
        //两种不同的方式创建
        UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn2.frame =btn2Frame;
        //设置Title
        [btn2 setTitle:@"BTN2" forState:UIControlStateNormal];
        [btn2 setTag:10001];
        //[btn2 setBackgroundImage:[UIImage imageNamed:@"pic.png"] forState:UIControlStateNormal];
        [btn2 setBackgroundColor:[UIColor blueColor]];
        [btn2 addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn2];
    
        //事件监听的问题
        CGRect btn1Frame = CGRectMake(200.0, 150.0, 60.0, 44.0);
        //两种不同的方式创建
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn1.frame =btn1Frame;
        //设置Title
        [btn1 setTitle:@"BTN1" forState:UIControlStateNormal];
        [btn1 setTag:10002];
        //[btn2 setBackgroundImage:[UIImage imageNamed:@"pic.png"] forState:UIControlStateNormal];
        [btn1 setBackgroundColor:[UIColor blueColor]];
        [btn1 addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn1];
    
    CGRect workingFrame;
    
    workingFrame.origin.x = 15;
    workingFrame.origin.y = 400;
    workingFrame.size.width = 140;
    workingFrame.size.height = 40;
    for(int i = 0; i < 6; i++)
    {
        //UIView *myView = [[UIView alloc] initWithFrame:workingFrame];
        UIButton *myView =[[UIButton alloc] initWithFrame:workingFrame];
        [myView setTag:i];//标记方块
        [myView setBackgroundColor:[UIColor blueColor]];
        // NSString tit = "Button"i;
        //NSLog(@"this is Button %d", i);
        [myView setTitle:@"Button %d" forState:UIControlStateNormal];
        workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width + 10;
        [myView addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:myView];
    }

在方法中使用tag选择器定位元素:

-(void)btnPressed:(id)sender{
    UIButton *thisBtn = (UIButton*)sender;
    //thisBtn.hidden = YES;
    //self.view viewWithTag:[00002];
     UIButton *myButton = (UIButton *)[self.view viewWithTag:(10002)];
    myButton.hidden = YES;
    NSLog(@"this button tag is %d",thisBtn.tag);
    //NSLog(@"self.view subViews %@",self.view.subviews);

//    UIButton* thisBtn = (UIButton *)sender;
//    [[[UIAlertView alloc] initWithTitle:@"Button" message:[NSString stringWithFormat: @"This is button:%@",thisBtn] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil] show];
//    NSLog(@"this tag is %d",btn.tag);
}


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页