如何在 NSObject 中创建 UIButton 及其@selector
How to create UIButton and its @selector in a NSObject
我正在尝试生成一个 class,它可以创建一个 UIButton 并处理当您在按钮所在的任何视图中按下按钮时发生的情况。这是我正在做的事情:
头文件:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CreateButton : NSObject
- (UIButton *)createButton;
@end
实施:
#import "CreateButton.h"
@implementation CreateButton
- (UIButton *)createButton
{
// Instanciate the class
CreateButton *classInstance = [[CreateButton alloc] init];
UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
[testButton setBackgroundColor:[UIColor redColor]];
[testButton addTarget:classInstance action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
return testButton;
}
- (void)buttonClicked:(UIButton *)sender
{
NSLog(@"Clicked");
}
@end
最后,在视图控制器中,我初始化 class 并获取按钮:
CreateButton *create = [[CreateButton alloc] init];
UIButton *testButton = [create createButton];
[self.view addSubview:testButton];
到目前为止一切正常,我可以看到按钮,但是,当我点击它时没有任何反应。令人惊讶的是,如果我将 buttonClicked:
方法移动到我的视图控制器,它就可以正常工作。我需要将所有按钮布线保留在 NSObject 中。任何帮助将不胜感激。
好的,我解决了这个问题,有趣。
执行文件将修改为:
- (UIButton *)createButton
{
UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
[testButton setBackgroundColor:[UIColor redColor]];
[testButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
return testButton;
}
然后,在视图控制器中,CreateButton
class 必须预先定义在头文件 @interface
部分。然后在执行中:
create = [[CreateButton alloc] init];
而且有效!如果您好心地向我解释一下,那就太好了。
我正在尝试生成一个 class,它可以创建一个 UIButton 并处理当您在按钮所在的任何视图中按下按钮时发生的情况。这是我正在做的事情:
头文件:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CreateButton : NSObject
- (UIButton *)createButton;
@end
实施:
#import "CreateButton.h"
@implementation CreateButton
- (UIButton *)createButton
{
// Instanciate the class
CreateButton *classInstance = [[CreateButton alloc] init];
UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
[testButton setBackgroundColor:[UIColor redColor]];
[testButton addTarget:classInstance action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
return testButton;
}
- (void)buttonClicked:(UIButton *)sender
{
NSLog(@"Clicked");
}
@end
最后,在视图控制器中,我初始化 class 并获取按钮:
CreateButton *create = [[CreateButton alloc] init];
UIButton *testButton = [create createButton];
[self.view addSubview:testButton];
到目前为止一切正常,我可以看到按钮,但是,当我点击它时没有任何反应。令人惊讶的是,如果我将 buttonClicked:
方法移动到我的视图控制器,它就可以正常工作。我需要将所有按钮布线保留在 NSObject 中。任何帮助将不胜感激。
好的,我解决了这个问题,有趣。
执行文件将修改为:
- (UIButton *)createButton
{
UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
[testButton setBackgroundColor:[UIColor redColor]];
[testButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
return testButton;
}
然后,在视图控制器中,CreateButton
class 必须预先定义在头文件 @interface
部分。然后在执行中:
create = [[CreateButton alloc] init];
而且有效!如果您好心地向我解释一下,那就太好了。