我有一个Xcode 5按钮问题。
我在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
指向action @ selector时出现错误“未声明的选择器viewDidLoad
”:
[hotelButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpOutside];
答案 0 :(得分:3)
使用此:
[hotelButton addTarget:self action:@selector(buttonClicked)
forControlEvents:UIControlEventTouchUpInside];
来自Apple Docs:
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);
}
答案 1 :(得分:1)
试试这个,
[hotelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
并传递发件人,
- (void) buttonClicked:(UIButton*)sender
{
NSLog(@"Button %i clicked", [sender tag]);
}
答案 2 :(得分:1)
尝试从外到内改变,
[hotelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
答案 3 :(得分: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];
}