查看此链接以了解iOS视图层次结构的基础知识:iOS视图 入门并了解下图(学分:techrepublic.com):
编程方式:
// Create your button wherever you wish (below is example button) UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; myButton.frame = CGRectMake(0.0, 0.0, 320, 450); [myButton setTitle:@"Yay" forState:UIControlStateNormal]; [myButton addTarget:self action:@selector(didTouchUp:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:myButton]; // This method will be called when touch up is made on the button - (void)didTouchUp:(UIButton *)sender { NSLog(@"Button Pressed!"); }
说明:
[myButton addTarget:self action:@selector(didTouchUp:) forControlEvents:UIControlEventTouchUpInside];
myButton - 您的按钮视图
addTarget - 方法所在的目标
action - 要调用的选择器
forControlEvents - 用户将执行的控制事件以触发此操作
使用故事板:
(A)确保故事板与正确的类对应
(B)将UIButton从对象库拖到故事板中
然后添加到ViewController.h文件:
#import@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *myButton; - (IBAction)didTouchUp:(id)sender; @end
然后添加到ViewController.m文件:
- (IBAction)didTouchUp:(id)sender { NSLog(@"Button Pressed!"); }
最后,在UIButton和IBAction之间创建连接:
(A)右键单击按钮视图
(B)将补救动作拖动到故事板上的按钮视图
(C)按didTouchUp:
这是完成这一步骤的基本流程......您可能希望通过阅读以下内容来扩展您的技能:
故事板与IB对比代码
斯坦福大学开发iOS