您的位置:首页 > 移动开发 > IOS开发

iOS开发经验技巧之IOS界面开发使用viewWithTag:(int)findTag方法获取界面元素

2015-06-16 17:04 615 查看
今天在开发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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tag ios开发 uiview