简体   繁体   中英

How to send method to view from action called by UIButton

I understand (I think) why this isn't working, but I don't know how to get it to work.

I have a method I call in viewWillAppear like so (I've simplified the code for the sake of this question):

- (void)viewWillAppear:(BOOL)animated
{
        [self displayHour:0];
}

I then have a little for loop that builds some buttons in viewDidLoad :

NSUInteger b = 0;

for (UIButton *hourButton in hourButtons) {
    [hourButton setTag:b];
    [hourButton setTitle:[NSString stringWithFormat:@"%lu", (unsigned long)b] forState:UIControlStateNormal];
    [hourButton addTarget:self action:@selector(showHour:) forControlEvents:UIControlEventTouchUpInside];

    b++;
}

Then for the action I have this:

- (IBAction)showHour:(id)sender
{
        // Logs 0, 1, etc. depending on which button is tapped
    NSLog(@"Button tag is: %lu", (long int)[sender tag]); 

    // This currently throws this error:
    // No visible @interface for 'UIView' declares the selector 'displayHour:'

    // What I want to do is be able to call this method on
    // the main view and pass along the button tag of the 
    // button that was tapped.
    [mainView displayHour:(long int)[sender tag]];
}

THE QUESTION is how do I call displayHour to the main view from the showHour: action?

If you need it, the displayHour method looks like this (simplified, basically updates some labels and image views on the main view):

- (void)displayHour:(NSUInteger)i
{    
    // The temperature
    hourTemp = [[hourly objectAtIndex:i] valueForKeyPath:@"temperature"];

    // The icon
    hourIcon = [[hourly objectAtIndex:i] valueForKeyPath:@"icon"];

    // The precipitation
    hourPrecip = [[hourly objectAtIndex:i] valueForKeyPath:@"precipProbability"];

    // SET DISPLAY
    [hourTempField setText:hourTemp];
    [hourIconFrame setImage:hourIcon];
    [hourPrecipField setText:hourPrecip];
}

Thanks!

Instead of

   [mainView displayHour:(long int)[sender tag]];

do:

   [self displayHour:(long int)[sender tag]];

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