2015-08-18 5 views
5

Pomóżcie mi, dostosowałem klasę UIView do ustawienia wartości NSString jako znacznika, ale jak mogę uzyskać ten widok z widoku hierarchii.W klasie UIView domyślną metodą uzyskania widoku jest viewWithTag:(NSInteger).Czy mogę dostosować istniejącą metodę viewWithTag: (NSInteger) dla stringTag?

proszę zobaczyć poniżej kod

#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 

Chcę metody takie jak viewWithStringTag:(NSString *)stringTag.

Dzięki,

Odpowiedz

5

Zastosowanie rekurencyjne wyszukiwania, zawiera 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 

Oto mój kod testowanie

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

Dzięki, Pozwól mi sprawdzić – Vishal16

+0

zwrot nie działa nil każdej chwili. – Vishal16

+0

Działa dobrze na moim projekcie testowym. Nic złego? @Vishu –

Powiązane problemy