我可以为stringTag自定义现有的viewWithTag:(NSInteger)方法吗?

Vis*_*l16 5 objective-c nsstring uiview viewwithtag swift

请帮帮我,我一直在自定义UIView类来将NSString值设置为标签,但是如何从视图层次结构中获取该视图.在UIView类中获取视图的默认方法是viewWithTag:(NSInteger).

请看下面的代码

#import <UIKit/UIKit.h>
@interface UIView (StringTag)
@property (nonatomic, copy) NSString *tagString;
@end

#import "UIView+StringTag.h"
#import <objc/runtime.h> 

static const void *tagKey = &tagKey;

@implementation UIView (StringTag)

- (void)setTagString:(NSString *)tagString
{
objc_setAssociatedObject(self, tagKey, tagString,OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (id)tagString
{
return objc_getAssociatedObject(self, tagKey);
}
@end
Run Code Online (Sandbox Code Playgroud)

我想要一个类似的方法viewWithStringTag:(NSString *)stringTag.

谢谢,

zy.*_*liu 5

使用递归搜索,包括self

#import <UIKit/UIKit.h>    

@interface UIView (StringTag)
@property (nonatomic, copy) NSString *tagString;    

- (UIView *)viewWithStringTag:(NSString *)strTag;    

@end    

#import "UIView+StringTag.h"
#import <objc/runtime.h>     

static const void *tagKey = &tagKey;    

@implementation UIView (StringTag)    

- (void)setTagString:(NSString *)tagString
{
    objc_setAssociatedObject(self, tagKey, tagString,OBJC_ASSOCIATION_COPY_NONATOMIC);
}    

- (id)tagString
{
    return objc_getAssociatedObject(self, tagKey);
}    

- (UIView *)viewWithStringTag:(NSString *)strTag{
    if ([self.tagString isEqual:strTag]){
        return self;
    }
    if (!self.subviews.count){
        return nil;
    }
    for (UIView *subview in self.subviews){
        UIView *targetView = [subview viewWithStringTag:strTag];
        if (targetView){
            return targetView;
        }
    }
    return nil;
}    

@end
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    aView.tagString = @"aView";
    UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    bView.tagString = @"bView";
    [self.view addSubview:aView];
    [aView addSubview:bView];

    UIView *targetView = [self.view viewWithStringTag:@"bView"];

    NSLog(@"%@", targetView);
    // <UIView: 0x7f933bc21e50; frame = (0 0; 100 100); layer = <CALayer: 0x7f933bc1c430>>
}
Run Code Online (Sandbox Code Playgroud)