2015-08-18 34 views
5

請幫助我,我一直在定製一個UIView類來設置NSString值作爲標記,但是我怎樣才能從視圖層次結構中獲得該視圖。在UIView類中獲取視圖的默認方法是viewWithTag:(NSInteger)我可以爲stringTag定製現有的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的方法。

感謝,

回答

5

使用遞歸搜索,包括自

#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>> 
} 
+0

謝謝你,讓我看一下零每次 – Vishal16

+0

不工作的回報。 – Vishal16

+0

在我的測試項目中正常工作。哪裏不對了? @Vishu –

相關問題