簡體   English   中英

我可以為stringTag自定義現有的viewWithTag:(NSInteger)方法嗎?

[英]Can I customize existing viewWithTag:(NSInteger) method for stringTag?

請幫助我,我一直在自定義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

我想要一個像viewWithStringTag:(NSString *)stringTag

謝謝,

使用遞歸搜索,包括自我

#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

這是我的測試代碼

- (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>>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM