代表成为无iOS

时间:2015-05-30 18:24:36

标签: ios objective-c delegates protocols

我使用上面的按钮创建了一个自定义UIView,此视图将作为viewcontroller的弹出窗口打开。我希望视图控制器拦截按钮的压力,所以我创建了一个协议方法,但是从不调用视图控制器中的委托。

协议:

@protocol InsertDelegate <NSObject>

-(void)addNode:(double)x pointY:(double)y radius:(double)r forw:(int)forw;
-(void)cancelView:(UIView*)view;

@end

在AddNewNode.h

@interface AddNewNode : UIView 

 @property (assign, nonatomic)id <InsertDelegate> delegate;

 - (IBAction)actionCancel:(id)sender;

 - (IBAction)actionAdd:(id)sender;
 @end

在AddNewNode.m

- (IBAction)actionCancel:(id)sender { //this action is connect with storyboard
     NSLog(@"%@", self.delegate);
     //(null)
    [self.delegate cancelView:self];
}

 - (IBAction)actionAdd:(id)sender { //this action is connect with storyboard
     NSLog(@"%@", self.delegate);
     //(null)
   [self.delegate addNode:x pointY:y radius:r forw:f];

 }

在ViewController.h中:

 @interface ViewController : UIViewController <InsertDelegate>

在ViewController.m中

 (IBAction)addNewNode:(id)sender {

       AddNewNode * addRowView =[[AddNewNode alloc]init];

       addRowView.delegate=self;
       [self.view addSubview: addRowView];

 }

 //delegate methods never called
 -(void)addNode:(double)x pointY:(double)y radius:(double)r forw:(int)forw{

 }
 -(void)cancelView:(UIView*)view{

 }

在UIView中,self.delegate变为null,我不明白为什么

2 个答案:

答案 0 :(得分:0)

如何为您的

制作IBOutlet
  

ViewController.h

@interface ViewController : UIViewController <InsertDelegate>

@property (strong, nonatomic) AddNewNode * addNewNode;
//or connect IBOutlet of your `addNewNode`
@property (strong, nonatomic) IBOutlet (addNewNode);

@end
  

ViewController.m

- (IBAction)addNewNode:(id)sender 
{
    // you dont need to allocate anymore
    self.addRowView.delegate=self;
    // and you need to trigger the delegate from `- (IBAction)actionAdd:(id)sender;`
    [self.addRowView actionAdd:sender];
}

答案 1 :(得分:-1)

尝试以下

创建一个私有属性来保存实例

@implement AddNewNode()
@propery (nonatomic, strong) AddNewNode * addNewNode;
@end

来自按钮处理程序

(IBAction)addNewNode:(id)sender {

   self.addNewNode =[[AddNewNode alloc]init];
   self.addRowView.delegate=self;

}