ios 以编程方式编码 UIButton 操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15054379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically code UIButton action
提问by Louis Holley
I'm trying to create a button, which once tapped will show a popover of another UIView. To test this out, I have the following code in my viewDidLoad section:
我正在尝试创建一个按钮,一旦点击该按钮将显示另一个 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];
}
and further down:
再往下:
- (IBAction) buttonClicked: (id)sender
{
NSLog(@"Tap");
}
however, the console does not log 'Tap' when I hit the button. Any ideas?
但是,当我按下按钮时,控制台不会记录“点击”。有任何想法吗?
回答by Odrakir
Watch these three lines of code:
看这三行代码:
hard1.layer.cornerRadius = 10;
hard1.clipsToBounds = YES;
[hard1 addTarget: self
action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];
You are missing self. in all three. They should be:
你缺少自我。在所有三个。他们应该是:
self.hard1.layer.cornerRadius = 10;
self.hard1.clipsToBounds = YES;
[self.hard1 addTarget: self
action: @selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];
Also, if you are creating it programatically, it shouldn't be an IBAction (IB stands for interface builder and this is not created in interface builder).
此外,如果您以编程方式创建它,它不应该是 IBAction(IB 代表界面构建器,这不是在界面构建器中创建的)。
回答by Kiran
self.hard1 = [UIButton buttonWithType:UIButtonTypeCustom];
[hard1 addTarget: self
action: @selector(buttonClicked:) forControlEvents: UIControlEventTouchUpInside];
Replace hard1 to self.hard1
将 hard1 替换为 self.hard1
回答by Srikar Appalaraju
You have put the event responder as buttonClicked
but in IBAction
you have defined buttonTap
. This would obviously not work...
您已将事件响应程序放置buttonClicked
在IBAction
您已定义的buttonTap
. 这显然行不通...
It should be
它应该是
[hard1 addTarget: self
action: @selector(buttonTap:)
forControlEvents: UIControlEventTouchUpInside];