iphone - 以编程方式编写 UIButton 操作代码

标签 iphone ios objective-c ipad uibutton

我正在尝试创建一个按钮,点击后将显示另一个 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”。有什么想法吗?

最佳答案

观察这三行代码:

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 代表界面构建器,它不是在界面构建器中创建的)。

关于iphone - 以编程方式编写 UIButton 操作代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15054379/

相关文章:

iphone - 在 IOS 中读取 Open-XML 文档

iphone - 如何检测特定区域的触摸

ios - Hook 系统 (libc) 在链接时在 iOS 上运行

ios - 检查在单元测试中传递给函数的参数值

objective-c - 将来自 AFHTTPRequestOperation 的响应传递给 UIWebview

ios - MFMailComposeViewController未在iOS 5中填充收件人

iphone - 提交应用到苹果应用商店后如何更改 "Version Release Control"

IOS Swift - 如何在具有不同数据的 Collection View 中使用 2 个 TableView

ios - SSL 固定 - 在 AFSecurityPolicy 中设置固定公钥而不是固定证书

ios - 将 subview 置于一切之上,但置于另一个 UIView 之下