0

我有一个 Xcode 5 按钮问题。

我以编程方式在 a 上创建了许多按钮UIViewController,然后想要注册对这些按钮的点击。我NSLog用来跟踪点击次数,但似乎日志中没有记录点击次数。

有人可以帮忙吗?

最终目标是UIViewController在每次按钮点击时继续下一步,但只是测试是否首先注册按钮点击。

这是我在其中创建按钮的方式viewDidLoad(仅显示 1 个)。注意:if-statement仅用于检查在前一个视图中按下了哪些按钮。

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.

    NSString *myString = [NSString stringWithFormat:@"%d", self.tagNumber ];

    if (self.tagNumber == 1)
    {
        hotelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        hotelButton.tag = 1;
        hotelButton.frame = CGRectMake(60, 60, 300.f, 100.f);

        UIImage *buttonImage1 = [UIImage imageNamed:@"buttonImage1.png"];
        [hotelButton setBackgroundImage:buttonImage1 forState:UIControlStateNormal];
        [self.view addSubview:hotelButton];

        // Add targets and actions
        [hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside];
    }

}

这是我检查按钮点击的方法

- (void) buttonClicked
{
    NSLog(@"Button %i clicked", hotelButton.tag);
}

注意:我还尝试了以下方法:

- (void) buttonClicked:(UIButton *) button
{
    NSLog(@"Button %ld clicked", (long int)[button tag]);
}

buttonClicked但这在我viewDidLoad指向 action@selector时给出了错误“未声明的选择器”):

[hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside];
4

4 回答 4

3

用这个:

[hotelButton addTarget:self action:@selector(buttonClicked) 
    forControlEvents:UIControlEventTouchUpInside];

来自苹果文档:

UIControlEventTouchUpInside
A touch-up event in the control where the finger is inside the bounds of the control.

UIControlEventTouchUpOutside
A touch-up event in the control where the finger is outside the bounds of the control

并保持这种方法:

- (void) buttonClicked
{
    NSLog(@"Button %i clicked", hotelButton.tag);
}
于 2013-10-31T09:03:55.177 回答
1

尝试这个,

[hotelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

并通过发件人,

- (void) buttonClicked:(UIButton*)sender
{
    NSLog(@"Button %i clicked", [sender tag]);
}
于 2013-10-31T09:05:11.283 回答
1

尝试从外到内改变,

[hotelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
于 2013-10-31T09:06:31.290 回答
1

已修改您的 if 条件。请关注:-

if (self.tagNumber == 1)
    {
        hotelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        hotelButton.tag = 1;
        hotelButton.frame = CGRectMake(60, 60, 300.f, 100.f);

        UIImage *buttonImage1 = [UIImage imageNamed:@"buttonImage1.png"];
        [hotelButton setBackgroundImage:buttonImage1 forState:UIControlStateNormal];
hotelButton.showsTouchWhenHighlighted = YES;
hotelButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:hotelButton];

    }
于 2013-10-31T09:22:36.363 回答