我以编程方式添加UIButton
,我想在按下时调用方法,我不确定如何设计这样的模式:
我应该在哪里放置事件处理程序或操作方法?在视图控制器或视图本身。
如果我将方法放在视图控制器中,如何在方法中操作View的SubViews
?我应该将所有SubViews
(UIButton
等)暴露给控制器,方法是将它们作为属性放入视图的头文件中吗?实际上这个问题应该以这种方式提出:我如何通过代码实现视图中的SubViews
通过Interface Builder与IBOutlet
属性相关联...
答案 0 :(得分:10)
检查此链接以了解iOS视图层次结构的基础知识: Getting started with iOS Views并了解下图(来源: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];
使用故事板:
然后添加到ViewController.h文件:
#import <UIKit/UIKit.h>
@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之间创建连接:
这是完成这一步骤的基本流程......您可能希望通过阅读以下内容来扩展您的技能: