我正在尝试在代码中创建一个 UIButton
,并且这段代码在某些方法中,这些方法将从某个类中调用。
这是创建按钮的方法
-(void)createButton
{
NSLog(@"createButton");
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Get Friends" forState:UIControlStateNormal];
[button setFrame:CGRectMake(100, 100, 100, 50)];
[button addTarget:self action:@selector(loadTableView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
但它从未出现在 View 中,怎么了?
编辑:如果我从 viewDidLoad
调用这个方法,它就可以工作了!
编辑 2:该方法在 ViewController 类中,我从 MyFacebooDelegate 类中调用它 这是来自 MyFacebooDelegate 类的调用代码:
ViewController *m2 = [[ViewController alloc] init];
[m2 createButton];
最佳答案
当您使用 ViewController *m2 = [[ViewController alloc] init];
创建一个新的 ViewController
时,它与 ViewController
不同正在处理屏幕。
您应该使用在应用程序启动时创建的 View Controller ,而不是分配一个 ViewController
。
关于objective-c - 在 Objective C 方法中创建 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245768/