如何从UIButton调用的动作发送方法来查看

时间:2013-10-05 22:16:08

标签: ios objective-c uibutton

我理解(我认为)为什么这不起作用,但我不知道如何让它发挥作用。

我有一个我在viewWillAppear中调用的方法(我为了这个问题简化了代码):

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

然后我有一个for循环,在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++;
}

然后我采取行动:

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

问题是如何通过displayHour操作将showHour:调用到主视图的?

如果你需要它,displayHour方法看起来像这样(简化,基本上更新主视图上的一些标签和图像视图):

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

谢谢!

1 个答案:

答案 0 :(得分:1)

而不是

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

做的:

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