那些年被viewwithtag坑过的朋友,过来看看了
- 在项目中肯定碰到过类似的情况,一排button,for循环生成,根据tag来辨别button , 但是当项目进行到中后期,代码量上来之后,老板突然跟你说,切换个按钮位置,得完蛋,你改了这个位置的viewwithtag之后,还有其他地方的,关键是你无法通过搜索得到,相同的操作,特别是还跨类的操作的时候,我现在想的,为什么要跨类去操作这些按钮,真的是S. B
- 我就想到如果,使用字符串来辨别view是不是更好咧,于是我实现了一个简单的类,如下:
//
// UIView+TagWithName.h
//
// Created by roy on 2018/7/19.
//
#import <UIKit/UIKit.h>
@interface UIView (TagWithName)
-(void)setName:(NSString*)name;
-(UIView*)viewWithName:(NSString*)name;
@end
//
// UIView+TagWithName.m
//
// Created by roy on 2018/7/19.
//
#import "UIView+TagWithName.h"
@implementation UIView (TagWithName)
//name 不得大于96个字符,只能保证通一个view里面不能有重名的,不能保证更上层或者是否含有这个重名
-(void)setName:(NSString *)name{
UIView *superView = [self superview];
NSUInteger tag = [name hash];
NSAssert(superView!=nil,@"this view must have a super view!");
UIView *otherView = [superView viewWithTag:tag];
NSAssert(otherView==nil,@"have same name in this view,please give other name");
self.tag = tag;
}
-(UIView*)viewWithName:(NSString *)name{
UIView *view = [self viewWithTag:[name hash]];
return view;
}
@end
github地址: https://github.com/Noying/ViewWithName
欢迎一起来研究,QQ 253807688