未调用UIButton目标操作

时间:2014-05-27 17:43:04

标签: ios objective-c uibutton target

请原谅我,如果这是微不足道的,我仍在磨练我的编程技巧。我正在尝试将此按钮设置为目标。应该很容易,但我不知道为什么它不起作用!我插入了一个NSLog进行测试,并且没有调用该方法!谢谢你的帮助。

//ShareView.h

@property (strong,nonatomic) UIButton *cancelBtn;


//ShareView.m
- (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code

            UIImage *shareImage = [UIImage imageNamed:@"shareBox.png"];
            [self setFrame:CGRectMake(10, 170, shareImage.size.width, shareImage.size.height)];

            self.shareIV = [[UIImageView alloc] initWithImage:shareImage];
            self.shareIV.userInteractionEnabled = YES;

            [self addSubview:self.shareIV];  

            [self shareBtnsInit];
            [self.shareIV addSubview:self.cancelBtn];

            self.userInteractionEnabled = YES;
        }
        return self;
}


-(void)shareBtnsInit{

        UIImage *cancelImg = [UIImage imageNamed:@"cancel27.png"];
        self.cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.cancelBtn setImage:cancelImg forState:UIControlStateNormal];
        [self.cancelBtn setFrame:CGRectMake(277, 3, cancelImg.size.width, cancelImg.size.height)];

}

//MainViewController.m

-(IBAction)settingsButtonPressed:(id)sender{
    self.shareVC = [[ShareView alloc] initWithFrame:CGRectMake(0, 0, 0,0)];
    [self.view addSubview: self.shareVC];

    [self.shareVC.cancelBtn addTarget:self action:@selector(settingsCancel:) forControlEvents:UIControlEventTouchUpInside];

}

-(IBAction)settingsCancel:(id)sender{
    NSLog(@"TEST!!!");
    [self.shareVC removeFromSuperview];
}

3 个答案:

答案 0 :(得分:1)

根据评论,您的settingsButtonPressed:方法未被调用,因此您正在寻找操作的按钮从未设置过。

答案 1 :(得分:0)

尝试将[self.cancelBtn addTarget:self action:@selector(settingsCancel:) forControlEvents:UIControlEventTouchUpInside];添加到您的shareBtnsInit方法中。

以下是有关以编程方式制作UIButtons的更多信息:How do I create a basic UIButton programmatically?

答案 2 :(得分:0)

[self.cancelBtn addTarget:MainViewController action:@selector(settingsCancel:) forControlEvents:UIControlEventTouchUpInside];

在ShareView中,您必须导入要在其中触发事件的类。 在ShareView中,您可以导入MainViewController类并可以使用它。