简体   繁体   English

从子类调用视图

[英]Calling views from subclasses

I have an iPhone app primarily made of two views, let's call them fullScreen and cardViews (the cardViews are presented as subViews of the full screen views). 我有一个主要由两个视图组成的iPhone应用程序,我们称它们为fullScreencardViewscardViews作为全屏视图的子视图显示)。 I've handled all of the animations in presenting the card Views by having a masterCardViewClass and a masterFullScreenViewClass . 我已经通过拥有masterCardViewClassmasterFullScreenViewClass来处理呈现卡视图的所有动画。 All specific cardViews are subclasses of the masterCardView, all specific fullScreenViews are subclasses of the masterFullScreenView. 所有特定的cardViews是masterCardView的子类,所有特定的fullScreenViews是masterFullScreenView的子类。

I present a cardView with a method from the masterFullScreenViewClass . 我用masterFullScreenViewClass中的方法介绍了masterFullScreenViewClass I dismiss the cardView with a delegate method from the masterCardView. 我用masterCardView中的委托方法关闭了CardView。 However, I'm having a problem calling a method to present a cardView from another cardView. 但是,我在调用一种方法来从另一个cardView呈现cardView时遇到问题。 All cardView presenting methods are contained in the masterFullScreenViewController class. 所有cardView呈现方法都包含在masterFullScreenViewController类中。

How do I access these methods without copying a pasting them locally where I need them. 如何访问这些方法,而又不将它们粘贴到需要的地方。

One way of doing it is by using protocols. 一种实现方法是使用协议。

In a nutshell, your masterCardView class would implement a protocol method that presents a cardView (for the sake of simplicity, let's say that you invoke cardViews with a certain index): 简而言之,您的masterCardView class将实现一个呈现cardView的协议方法(为简单起见,假设您使用特定索引调用cardViews):

masterCardView.h: masterCardView.h:

@protocol CardPresenterDelegate <NSObject>

- (void)presentCardViewWithIndex:(int)index;

@end

@interface MasterCardView:UIViewController <CardPresenterDelegate>
...

masterCardView.m: masterCardView.m:

- (void)presentCardViewWithIndex:(int)index
{
// Code for presenting a cardView
}

You would also need to create a delegate (weak) property in your cardView: 您还需要在cardView中创建一个委托(弱)属性:

cardView.h cardView.h

@property (weak) id<CardPresenterDelegate> cardPresenterDelegate;

And then by accessing that property in your cardView, you can tell the masterCardView to do something for you: 然后通过访问cardView中的该属性,可以告诉masterCardView为您做一些事情:

cardView.m cardView.m

[self.cardPresenterDelegate presentCardViewWithIndex:5];

Oh, and, don't forget to set the delegate property on your cardViews when creating them in your masterCardView: 哦,而且,在masterCardView中创建它们时,请不要忘记在cardViews上设置委托属性:

back in masterCardView.m: 回到masterCardView.m:

cardView.cardPresenterDelegate = self;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM