在子视图中调用方法

问题描述:

嘿家伙!我有这个小问题:在子视图中调用方法

我有一个视图控制器它增加了2子视图在我的视图控制器,所以我有这样的事情:

//in my viewController.m i have this: 
- (void)startIcons 
{ 
    IconHolder *newIconHolder = [[IconHolder alloc] initWithItem:@"SomeItenName"]; 
    [self.view addSubview:newIconHolder]; 
} 
- (void)onPressIcon targetIcon(IconHolder *)pressedIcon 
{ 
    NSLog(@"IconPressed %@", [pressedIcon getName]); 
} 

这是我的子类沾上:

//And in my IconHolder.m i have this: 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Here i need to call the method onPressIcon from my ViewController 
} 

现在: 我该怎么做?最好的方法是在我的构造函数中创建一个链接来保存我的ViewController?我该怎么做?

谢谢!

是的,您应该创建该链接,就像您怀疑的一样。

只需将成员变量MyViewController* viewController添加到您的视图中,并在创建视图时进行设置。如果你想变得聪明,你可以创建它作为一个属性。

请注意,您不应该从视图中保留viewController,尽管 - 视图已被控制器保留,并且如果保留以其他方式进行,您将生成一个保留循环并导致泄漏。

创建链接的替代方法是使用通知。

例如,在IconHolder.h

extern const NSString* kIconHolderTouchedNotification; 

在IconHolder.m

常量的NSString * kIconHolderTouchedNotification = @ “IconHolderTouchedNotification”;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Here i need to call the method onPressIcon from my ViewController 
    [[NSNotificationCenter defaultCenter] kIconHolderTouchedNotification object:self]; 
} 
在控制器

然后

- (void) doApplicationRepeatingTimeChanged:(NSNotification *)notification 
{ 
    IconHolder* source = [notification object]; 
} 

- (IBAction) awakeFromNib; 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doIconHolderTouched:) name:kIconHolderTouchedNotification object:pressedIcon]; 
} 

- (void) dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self name: kIconHolderTouchedNotification object:pressedIcon]; 
    [super dealloc]; 
} 

通知,如果你想让对象之间非常弱联动,不需要双向通信(即IconHolder并不需要问的信息,控制器特别好),或者如果您需要通知多个对象的更改。