简体   繁体   中英

UIButton target action not being called

Forgive me if this is trivial, I am still honing my programing skills. I am trying to set this button as a target. Should be easy but I dont know why it's not working! I inserted a NSLog to test and the method is not being called! Thanks for your help.

//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];
}

基于注释,没有调用settingsButtonPressed:方法,因此从未设置要查找操作的按钮。

Try adding [self.cancelBtn addTarget:self action:@selector(settingsCancel:) forControlEvents:UIControlEventTouchUpInside]; to your shareBtnsInit method.

Here's more information on making UIButtons programatically: How do I create a basic UIButton programmatically?

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

In ShareView you have to import class in which you want your event should get triggered. Here in ShareView you can import MainViewController class and can use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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