【发布时间】:2016-12-30 06:08:09
【问题描述】:
我正在尝试生成一个可以创建 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
最后,在视图控制器中,我初始化类并获得按钮:
CreateButton *create = [[CreateButton alloc] init];
UIButton *testButton = [create createButton];
[self.view addSubview:testButton];
到目前为止一切正常,我可以看到按钮,但是当我单击它时没有任何反应。令人惊讶的是,如果我将 buttonClicked: 方法移动到我的视图控制器,它就可以正常工作。我需要将所有按钮接线保留在 NSObject 中。任何帮助将不胜感激。
【问题讨论】:
标签: objective-c xcode uibutton nsobject