关于viewWithTag的使用

http://blog.csdn.net/me10net/article/details/9324327

 

通常我们使用viewWithTag如下情形:

如果我们用了一个父View,上面放了多个子view, 每个子view都通过从0开始的Tag值来进行标志,以便于后期在像View上直接使用viewWithTag:tag值来取各个子View

而在用[父view viewWithTag:0]取到的view, 发现不是子view, 而是这个父view, 

后来才想起苹果文档上提到过一次,tag值较小的,如0-100为苹果保留使用, 而0就是保留着给自己这个view使用的。

对于其它的view, 如scrollview, 则更上面的0, 1,2 都可能会是保留值。 

所以在使用viewWithTag时, 和在设置子view的Tag值时, 需要注意不要使用数值较小的Tag值,使用时建议加一个定值

 

#define TileInitialTag          10000

使用时,如下

curTileView_0.tag = TileInitialTag + emptyPlaceIndex_0;

这样就可以有效地避免因为tag值太小,而取到系统保留的view.

 

 

通常我们在初始化页面后,在UIView 上动态的添加多个子 View 时,又没设置类成员变量,在相关的操作中又要使用到那些子视图的控件。这时我们就可以用 viewWithTag 这个方法来获取相关子视图的变量,以方便操作。

类似例子:

UIImageView *leftMsgBg = [[[UIImageViewalloc] initWithFrame:CGRectMake(0, 0, 17, 37)]autorelease];
[leftMsgBg setImage:[UIImageimageNamed:@"bg_camera_left"]];
leftMsgBg.tag = 123;
UIImageView *midMsgBg = [[[UIImageViewalloc] initWithFrame:CGRectMake(17, 0, 85, 37)]autorelease];
// [midMsgBg setImage:[UIImage imageNamed:@"bg_camera"]];
[midMsgBg setBackgroundColor:[UIColorgrayColor]];
midMsgBg.tag = 124;
UIImageView *rightMsgBg = [[[UIImageViewalloc] initWithFrame:CGRectMake(102, 0, 17,37)]autorelease];
[rightMsgBg setImage:[UIImageimageNamed:@"bg_camera_right"]];
rightMsgBg.tag = 125;
UILabel * lab = [[[UILabelalloc]initWithFrame:CGRectMake(20, 0, 65, 37)]autorelease];
lab.text = @”新消息!!!”;
lab.tag = 126;
[lab setFont:[UIFontboldSystemFontOfSize:14]];
[lab setBackgroundColor:[UIColorclearColor]];
[lab setTextColor:[UIColoryellowColor]];
 
[self.newMsgBgaddSubview:leftMsgBg];
[self.newMsgBgaddSubview:midMsgBg];
[self.newMsgBgaddSubview:rightMsgBg];
[self.newMsgBgaddSubview:lab];

UIImageView *leftMsgBg = (UIImageView *)[self.newMsgBgviewWithTag:123];
UIImageView *midMsgBg = (UIImageView *)[self.newMsgBgviewWithTag:124];
UILabel * lab = (UILabel *)[self.newMsgBgviewWithTag:126];

 

转载于:https://www.cnblogs.com/smallyin00/p/3217111.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值