以编程方式编写UIButton操作

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”。有任何想法吗?

IOS 14 SDK:您可以使用闭包回调添加操作: - Ucdemir
3个回答

12

看这三行代码:

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

你在所有三个地方都缺少了self.。它们应该是这样的:
self.hard1.layer.cornerRadius = 10;
self.hard1.clipsToBounds = YES;
[self.hard1 addTarget: self
          action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];

此外,如果您是通过编程创建它,它不应该是一个IBAction(IB代表接口构建器,这不是在接口构建器中创建的)。

1
既然我现在在做这个。当你创建一个属性时,在synthesize中加入以下内容:@synthesize hard1 = _hard1; 这样只是用"hard1"来引用该属性是不起作用的,只能使用self.hard1或_hard1(只能在setter方法中使用后者)。 - Odrakir

4
    self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];


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

将 hard1 替换为 self.hard1。


0

你把事件响应器命名为buttonClicked,但在IBAction中你定义了buttonTap。显然这是行不通的...

应该是

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

我打错了一个字。我的实际代码已经编辑在上面,但仍然无法工作。 - Louis Holley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接