我正在开发一个蛇游戏,为此我创建了3个类:Player,Control和Grid。对于我的问题,我想以编程方式创建播放按钮,其中创建按钮的功能在Control类中,并且此函数在ViewController.m中调用
在ViewController.h中,我定义了
@property (nonatomic, strong) Control *control; //object of Control class
@property (weak) IBOutlet UIButton *button;
在ViewController.m中:
self.control = [[Control alloc] init];
[control createButton:_viewC Button:_button]; //_viewC is the view where the button will be shown
[_button addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside]; //since play method in ViewController.m
在Control类中:
-(void)createButton:(UIView*)view Button:(UIButton*)button
{
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"Play" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal ];
button.backgroundColor = [UIColor whiteColor];
button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];
button.layer.cornerRadius = 10;
button.frame = CGRectMake(35, 30, 70, 40);
[view addSubview:button];
}
问题是当我运行游戏并按下按钮时,不会发生任何动作!有人可以帮我弄这个吗。感谢
答案 0 :(得分:0)
假设'play'方法中的代码是正确的,您可以尝试通过将声明更改为:
来设置Control类中的目标。-(void)createButton:(UIView*)view Button:(UIButton*)button Selector:(SEL)selector
然后在该方法中添加:
[button addTarget:self.superview action:selector forControlEvents:UIControlEventTouchUpInside];
最后在ViewController.m中将行更改为:
[control createButton:_viewC Button:_button selector:@selector(play)];
并删除下面的行。