0

我有一个 MYView 类(UIView 的子类),我将 MyView 作为子视图添加到我当前的 ViewController 中。MyView 有一个按钮,如果触发了 TouchUpInsideEvent,它会调用委托方法。我的问题是,当我点击按钮时,控件转到委托方法,但是如果我触发 TouchUpinsideEvent prgramaticaaly,它不会调用委托方法。这是我的代码:

我的视图.h

@protocol MyViewDelegate;
@interface MyView : UIView
@property(nonatomic,assign)id<MyViewDelegate> delegate;

@protocol MyViewDelegate <NSObject>
- (void)selctedOption:(MyView *)slideView withOption:(UILabel *)option withIndex:   (NSInteger *)labelIndex;

@end

我的视图.m

toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[toggleButton setTitle:@"" forState:UIControlStateNormal];


//adding target works fine it goes to the finishedDraggingVertical:withEvent method and from there I am calling the delegate method

[toggleButton addTarget:self action:@selector(finishedDraggingVertical:withEvent:)
       forControlEvents:UIControlEventTouchUpInside];

toggleButton.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);

toggleButton.backgroundColor=[UIColor colorWithRed:0.1 green:1.1 blue:0.3 alpha:0.2];
[toggleButton.layer setBorderWidth:10.0];
[toggleButton.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
toggleButton.layer.cornerRadius=10.0;



[self addSubview:toggleButton];
 **//But If I fire the event programatically this doesn't work it goes to finishedDraggingVertical:withEvent but from there it does not go to the delegate method.**
 [toggleButton sendActionsForControlEvents:UIControlEventTouchUpInside]

MyViewController.h

@interface MyViewController : UIViewController  <MyViewDelegate>

我的视图控制器.m

//这里我添加myView并实现委托方法

- (void)viewDidLoad
{
 [super viewDidLoad];
 MyView *myiew1=[[MyView alloc]init];
 myiew1.delegate=self;

[self.view addSubview:slideView1];
}
4

2 回答 2

1

我知道这是一种解决方法,但是您是否尝试过以下问题的公认答案:

UIControl:sendActionsForControlEvents 省略 UIEvent

此外,检查您检索的操作是否[self actionsForTarget:target forControlEvent:controlEvent]与您之前在代码中设置的操作一致。如果没有,那就有问题了。

于 2013-03-14T08:38:03.983 回答
0

发生这种情况可能是因为您在调用后设置了委托:

 [toggleButton sendActionsForControlEvents:UIControlEventTouchUpInside];

我假设您在视图的initorinitWithFrame方法中添加了 toggleButton,并且上面的代码行也在同一行中。

delegate如果您在内部的委托方法调用之前打印出对象finishedDraggingVertical:withEvent,您可能会得到Nil.

于 2013-03-14T08:43:59.587 回答