如何通过编码创建的按钮调用方法

时间:2013-06-10 08:11:48

标签: iphone objective-c

我是新鲜的iphone ..我创建了一个按钮并通过编码并想通过该按钮调用方法我该怎么办请帮助我..

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(20, 20, 150, 44); // position in the parent view and set the size of the button
[myButton setTitle:@"Click Me!" forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
// add to a view
[myview addSubview:myButton];

5 个答案:

答案 0 :(得分:2)

答案就在于问题本身

// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

此行向按钮添加了一个操作,该按钮位于self,其行为名称buttonClicked:用于控制touchUpInside

所以当按钮触摸时,它将执行方法buttonClicked

因此

- (void)buttonClicked: (UIButton *)sender
{
 // do whatever you want to do here on button click event
}

将在按钮操作

上执行

答案 1 :(得分:1)

- (void)buttonClicked:(id)sender
{
   // your code
}

答案 2 :(得分:0)

- (void)buttonClicked: (UIButton *)sender
{
 // do stuff
}

答案 3 :(得分:0)

查看UIControl documentation

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents  

操作: A selector identifying an action message. It cannot be NULL.

您正在传递@selector(buttonClicked:)作为操作。 @selector()是一个编译器指令,用于将括号内的任何内容转换为SELSEL是指示方法名称的类型,但不是方法实现。[1]因此在您的班级中实施-(void)buttonClicked:(id)sender

答案 4 :(得分:0)

- (void)buttonClicked: (UIButton *)sender
{
 // do whatever you want to do here on button click event
}