xCode:从动态添加的子视图中激活IBAction

时间:2012-10-13 13:37:00

标签: xcode uiview uibutton

我有一个单独的UIView类,它构造一个包含UIButton的简单页脚栏。

  - (id)initWithFrame:(CGRect)frame
  {
    self = [super initWithFrame:CGRectMake(0, 410, 320, 50)];
    if (self) {
      int buttonHeight = self.frame.size.height;
      int buttonWidth = 70;
      int nextBtnPosX =0;
      int nextBtnPosY =0;


      self.backgroundColor =[UIColor colorWithRed:254.0/255.0 green:193.0/255.0 blue:32.0/255.0 alpha:1.0];
      [self sendSubviewToBack:self];
      UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      [nextBtn setTitle:@"Next" forState:UIControlStateNormal];
      nextBtn.frame = CGRectMake(nextBtnPosX, nextBtnPosY, buttonWidth, buttonHeight);
      [nextBtn addTarget:self.superview action:@selector(GoToNextPage) forControlEvents:UIControlEventTouchUpInside];   

      [self addSubview:nextBtn];

    }
    return self;
  }

我有几个ViewControllers,然后将上面的页脚视图类作为子视图添加到每个视图。

  UIView *newFooter = [[theFooter alloc] init];
  [self.view addSubview:newFooter];

现在页脚视图中的实际UIButton需要为添加到的每个viewController使其taget不同。

所以我虽然最好将IBAction添加到实际的视图控制器中,然后通过页脚视图调用它。

但这是我遇到问题的地方。如何从addTarget中调用父控制器从页脚子视图中初始化IBAction(GoToNextPage)?

在页脚子视图中将所有内容全部放入并传递所需的目标也会更容易,如果是这样,那么还有什么办法呢。

1 个答案:

答案 0 :(得分:1)

以下是您应该做的大致概述。 这就是你的UIView的头文件看起来的样子

@protocol myViewControllerDelegate <NSObject>
@optional
- (void)didPushButton:(id)sender;
@end

@interface UIViewController : UITableViewController
{
    __unsafe_unretained id <myViewControllerDelegate> delegate;
}

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

@end

请记住主文件中的@synthesize delegate;

最后在您的主文件中,您将拥有一个接收UIButton操作的IBAction。 假设该动作名为buttonPushed。

将该操作设置为:

- (IBAction)buttonPushed:(id)sender
{
    if (delegate)
        [delegate didPushButton:sender];
}

最后请记住,您需要将委托设置为使用此viewController的每个viewController。

UIView *newFooter = [[theFooter alloc] init];
[self.view addSubview:newFooter];
newFooter.delegate = self;
相关问题