Objective C: Sending arguments to a method called by a UIButton

后端 未结 6 767
甜味超标
甜味超标 2021-01-06 10:26

I have a method that is being called when a UIButton is clicked. When I create the button I want it to store an NSTimer as an argument.

This is the timer and the cr

6条回答
  •  情深已故
    2021-01-06 11:08

    You need to make the timer a property of your view controller and then referenced it from your tapFig: method. Here is what your code might look like:

    MainViewController.h

    //
    //  MainViewController.h
    //  TapFigSample
    //
    //  Created by Moshe Berman on 1/30/11.
    //  Copyright 2011 MosheBerman.com. All rights reserved.
    //
    
    @interface MainViewController : UIViewController  {
        NSTimer *timer; 
        UIButton *stickFig;
    }
    
    @property (nonatomic, retain) NSTimer *timer;
    @property (nonatomic, retain) UIButton *stickFig;
    
    - (void)tapFig:(id)sender;
    
    - (void) moveStickFig;
    
    - (void) moveStickFig:(id)yourArgument
    
    
    @end
    

    MainViewController.m

    //
    //  MainViewController.m
    //  TapFigSample
    //
    //  Created by Moshe Berman on 1/30/11.
    //  Copyright 2011 MosheBerman.com. All rights reserved.
    //
    
    #import "MainViewController.h"
    
    
    @implementation MainViewController
    
    @synthesize timer, stickFig;
    
    - (void) viewDidLoad{
    
        [self  setTimer:[NSTimer scheduledTimerWithTimeInterval:(0.009) target:self selector:@selector(moveStickFig:) userInfo:stickFig repeats:YES]];
        [stickFig addTarget:self action:@selector(tapFig:) forControlEvents:UIControlEventTouchUpInside];
    
    }
    
    - (void)tapFig:(id)sender{
        //do something with self.timer
    
    }
    
    - (void) moveStickFig:(id)yourArgument{
        //Move the stick figure
        //A tophat and a cane might 
        //look nice on your stick figure
        // :-)
    }
    
    - (void)dealloc {
        [stickFig release];
        [timer release];
        [super dealloc];
    }
    
    
    @end
    

    Notice the @property declaration in the header file. I'd consider taking another look at the timer initialization too, but that could just be me. I hope this helps!

提交回复
热议问题