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

http://blog.csdn.net/lxp1021/article/details/43952551

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

界面元素打tag

  1. //事件监听的问题
  2. CGRect btn2Frame = CGRectMake(100.0, 150.0, 60.0, 44.0);
  3. //两种不同的方式创建
  4. UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  5. btn2.frame =btn2Frame;
  6. //设置Title
  7. [btn2 setTitle:@"BTN2" forState:UIControlStateNormal];
  8. [btn2 setTag:10001];
  9. //[btn2 setBackgroundImage:[UIImage imageNamed:@"pic.png"] forState:UIControlStateNormal];
  10. [btn2 setBackgroundColor:[UIColor blueColor]];
  11. [btn2 addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
  12. [self.view addSubview:btn2];
  13. //事件监听的问题
  14. CGRect btn1Frame = CGRectMake(200.0, 150.0, 60.0, 44.0);
  15. //两种不同的方式创建
  16. UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  17. btn1.frame =btn1Frame;
  18. //设置Title
  19. [btn1 setTitle:@"BTN1" forState:UIControlStateNormal];
  20. [btn1 setTag:10002];
  21. //[btn2 setBackgroundImage:[UIImage imageNamed:@"pic.png"] forState:UIControlStateNormal];
  22. [btn1 setBackgroundColor:[UIColor blueColor]];
  23. [btn1 addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
  24. [self.view addSubview:btn1];
  25. CGRect workingFrame;
  26. workingFrame.origin.x = 15;
  27. workingFrame.origin.y = 400;
  28. workingFrame.size.width = 140;
  29. workingFrame.size.height = 40;
  30. for(int i = 0; i < 6; i++)
  31. {
  32. //UIView *myView = [[UIView alloc] initWithFrame:workingFrame];
  33. UIButton *myView =[[UIButton alloc] initWithFrame:workingFrame];
  34. [myView setTag:i];//标记方块
  35. [myView setBackgroundColor:[UIColor blueColor]];
  36. // NSString tit = "Button"i;
  37. //NSLog(@"this is Button %d", i);
  38. [myView setTitle:@"Button %d" forState:UIControlStateNormal];
  39. workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width + 10;
  40. [myView addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
  41. [self.view addSubview:myView];
  42. }

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

    1. -(void)btnPressed:(id)sender{
    2. UIButton *thisBtn = (UIButton*)sender;
    3. //thisBtn.hidden = YES;
    4. //self.view viewWithTag:[00002];
    5. UIButton *myButton = (UIButton *)[self.view viewWithTag:(10002)];
    6. myButton.hidden = YES;
    7. NSLog(@"this button tag is %d",thisBtn.tag);
    8. //NSLog(@"self.view subViews %@",self.view.subviews);
    9. //    UIButton* thisBtn = (UIButton *)sender;
    10. //    [[[UIAlertView alloc] initWithTitle:@"Button" message:[NSString stringWithFormat: @"This is button:%@",thisBtn] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil] show];
    11. //    NSLog(@"this tag is %d",btn.tag);
    12. }
上一篇:第一百五十七节,封装库--JavaScript,预加载图片


下一篇:CSS盒子模型之CSS3可伸缩框属性(Flexible Box)