7

我正在尝试创建一个按钮,一旦点击它将显示另一个 UIView 的弹出窗口。为了测试这一点,我在 viewDidLoad 部分中有以下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.hard1 setFrame:CGRectMake(884, 524, 105, 60)]; // set the x,y,width and height based on your specs
    UIImage *buttonImage = [UIImage imageNamed:@"green.jpg"];
    hard1.layer.cornerRadius = 10;
    hard1.clipsToBounds = YES;
    [hard1 addTarget: self
              action: @selector(buttonClicked:)
    forControlEvents: UIControlEventTouchUpInside];
    [self.hard1 setImage:buttonImage forState:UIControlStateNormal];
    [self.view addSubview:self.hard1];
}

再往下:

- (IBAction) buttonClicked: (id)sender
{
    NSLog(@"Tap");
}

但是,当我按下按钮时,控制台不会记录“Tap”。有任何想法吗?

4

3 回答 3

12

看这三行代码:

hard1.layer.cornerRadius = 10;
hard1.clipsToBounds = YES;
[hard1 addTarget: self
          action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];

你缺少自我。在所有三个。他们应该是:

self.hard1.layer.cornerRadius = 10;
self.hard1.clipsToBounds = YES;
[self.hard1 addTarget: self
          action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];

此外,如果您以编程方式创建它,它不应该是 IBAction(IB 代表界面构建器,它不是在界面构建器中创建的)。

于 2013-02-24T17:34:29.993 回答
3
    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];


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

将 hard1 替换为 self.hard1

于 2013-02-24T17:44:59.807 回答
0

您已将事件响应者buttonClicked置于IBAction您已定义buttonTap的 . 这显然行不通……

它应该是

[hard1 addTarget: self
              action: @selector(buttonTap:)
    forControlEvents: UIControlEventTouchUpInside];
于 2013-02-24T17:31:31.867 回答