事实上,许多人更喜欢以编程方式而不是使用 Interface Builder 来创建他们的 UI——.xib 文件不能很好地与版本控制配合使用。首先,您可以创建一个自定义 UIViewController 类,并在您的 App Delegate 的应用程序中使用类似以下内容:didFinishLaunchingWithOptions: 方法
CustomViewController* myCustomViewController = [[CustomViewController alloc] init];
self.window.rootViewController = myCustomViewControllerObject;
您可以在其 init、viewDidLoad 和其他方法中设置您的自定义视图控制器类以满足您的需求。要添加大多数界面元素,您可以使用其适当的方法(例如,用于视图的 initWithFrame:)初始化它们,然后将它们添加到您的 viewController 的视图中。有很多方法可以做到这一点,但最终您将调用要添加到的 UIView 的 addSubView: 方法。为了模拟大多数 UI 元素的 IBAction 链接,您调用 addTarget:action:forControlEvents:,并实现为 action 参数传递的选择器。这是 UIViewController 的 init 方法的示例:
-(id) init
{
(if self = [super init]) {
UIButton* addSelectedButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
[addSelectedButton setTitle: @"Some Button Title" forState: UIControlStateNormal];
addSelectedButton.frame = CGRectMake(sizeForTable.size.width/2 - 100 , sizeForTable.size.width/2 + 40, 200, 40);
[addSelectedButton addTarget: self action: @selector(addSelectedButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubView: addSelectedButton];
}
return self
}
-(void) addSelectedButtonPressed: (UIEvent*) event
{
//do something
}