如何仅使用代码正确地将按钮添加到场景中?

时间:2015-07-22 17:26:05

标签: ios objective-c uibutton

解决其他堆栈溢出问题我已设法提出以下代码。

(在我的homescreen.m文件中)

 UIButton *GCButton;


 -(id)initWithSize:(CGSize)size {
     if (self = [super initWithSize:size]) {

         //add button
         [self addGameCenterButton];


     }
     return self;
 }



 -(void)addGameCenterButton
 {
     GCButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
     [GCButton setBackgroundColor:[UIColor orangeColor]];
     [GCButton setTitle: @"My Button" forState:UIControlStateNormal];
     [GCButton setTitleColor: [UIColor blueColor] forState:UIControlStateNormal];
     [GCButton.layer setBorderWidth:1.0f];
     [GCButton.layer setBorderColor:[UIColor blueColor].CGColor];
     //adding action programatically
     [GCButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:GCButton];   
 }

 -(void)buttonClicked:(UIButton*)sender
 {
     NSLog(@"you clicked on button %ld", (long)sender.tag);
 }

截至目前,我在屏幕上看不到任何内容。是否需要在我的.m或.h文件中添加其他任何内容才能使按钮正常工作?

先谢谢您的帮助

1 个答案:

答案 0 :(得分:1)

根据您的问题的评论,我假设您正在使用SpriteKit。遗憾的是,在GameScene中,您无法正常使用UIButtons

要为您的场景创建按钮,请查看以下链接中的答案: Setting up buttons in SKScene