我是新來的ObjC,我試圖在ViewController文件之外創建按鈕(遵循MVC範例)。 我做了什麼:UIButton和UIViewContoller IOS7
.H
@interface MainMenu : UIButton
-(UIButton *)addButton;
@end
.M
@implementation MainMenu
-(UIButton *)addButton {
UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(50.0, 50.0, 200.0, 75.0)];
[button setBackgroundColor:[UIColor colorWithRed:1.0
green:1.0
blue:0.0
alpha:1.0]];
[button setTitle:@"TITLE"
forState:UIControlStateNormal];
return button;
}
@end
在視圖控制器我想在屏幕上創建按鈕,使響應觸摸事件。所以
.m
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
MainMenu *menuButton = [[MainMenu alloc] init];
[menuButton addTarget:self
action:@selector(ButtonClick)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:menuButton];
}
-(void)ButtonClick {
NSLog(@"You clicked on button!!!");
}
@end
我可以通過在ViewController.m文件中實現所有,但希望我可以然後分離。第二件事:我試圖添加addTarget:action:forControlEvents:方法到MainMenu.m而不是ViewController.m,我無法使它正常工作,因爲我需要傳遞ViewController作爲一個按鈕。目標和方法ButtonClick從ViewController.m作爲選擇器(我猜)
所以我很有趣如何使它正確的根據MVC? 謝謝!
謝謝!它看起來不錯,但我想將setFrame行移到MainMenu.h會更好。 – johann 2014-10-11 17:56:07
我不同意。你很少想在其子類中設置UIView的框架。最好從添加它的視圖中明確地設置它。假設您希望將來在您的應用程序的不同UIViewContoller中重用MainMenu。你可能想要在UIViewContoller中有一個不同的框架。切勿在子類內設置框架。 – dfmuir 2014-10-11 17:58:42
我理解你的立場,但我可以將Frame作爲參數傳遞,我將在稍後執行。謝謝! – johann 2014-10-11 18:09:02