简体   繁体   English

对委托模式感到困惑

[英]confused about delegate pattern

I'm creating a custom UIView subclass ( shareView ) from a Nib. 我正在从Nib创建自定义UIView子类( shareView )。 I created a custom protocol for shareView like this: 我为shareView创建了一个自定义协议,如下所示:

@protocol sharePopupDelegate
@required

-(void)userPublishedContent;
-(void)userAbortedPublish;

@end

@interface shareView : UIView
{
     id<sharePopupDelegate> delegate;
}    

In my main.storyboard I created a custom UIViewController myViewController with a shareView view instance called " popup " inside. 在我的main.storyboard中,我创建了一个自定义UIViewController myViewController,其中包含一个名为“ popup ”的shareView视图实例。

So now I got 所以现在我得到了

@property (weak, nonatomic) IBOutlet shareView *popup;

I would like now to delegate myViewController from shareView methods i declared, so I did 我现在想从声明的shareView方法中委派myViewController ,所以我做了

self.popup.delegate = self;

inside myViewController but the protocols' methods are not being called inside myViewController. 在myViewController内部,但是未在myViewController内部调用协议的方法。

So i correctly see the shareView instance but cannot interface to its delegate. 所以我正确地看到了shareView实例,但是无法连接到其委托。

Can you help me please? 你能帮我吗?

Thanks in advance 提前致谢

Make sure that you have the protocol declared in myViewController. 确保您具有在myViewController中声明的协议。

For example 例如

   @interface MyViewController : UIViewCOntroller <sharePopupDelegate>

In this section of the code: 在这段代码中:

@interface shareView : UIView
{
     id<sharePopupDelegate> delegate;
}   

You are creating a strong reference to the delegate, which is not what you want most of the time. 您正在创建对委托的强大引用,这在大多数情况下不是您想要的。 Change it to this: 更改为此:

@interface shareView : UIView
@property(weak, nonatomic) id<sharePopupDelegate> delegate;

The shareView class itself must have some way to know when a user publishes content. shareView类本身必须具有某种方法来知道用户何时发布内容。 Maybe you have an action linked up to the shareView which calls a method in the shareView class. 也许您有一个链接到shareView的操作,该操作调用了shareView类中的方法。 For examaple: 例如:

- (void)publishButtonTapped {
// some code
}

What you want to do is let the delegate know in that method, something like this: 您要做的是让委托人知道该方法,如下所示:

- (void)publishButtonTapped {

// some code
[self.delegate userPublishedContent];
}

Then whatever action the user takes to cancel: 然后,用户采取任何取消操作:

- (void)cancelButtonTapped {

// some code
[self.delegate userAbortedPublish];
}

Hope this helps. 希望这可以帮助。

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

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