Objective c UIView中的UIButton未响应
单击视图中的UIButton时,它没有响应。某个数字 我做错了什么?这是我的全部代码:Objective c UIView中的UIButton未响应,objective-c,uiview,Objective C,Uiview,单击视图中的UIButton时,它没有响应。某个数字 我做错了什么?这是我的全部代码: MyView.h @interface Myview : UIView @end MyView.m #import "MyView.h" - (init){ self = [super init]; if(self) [self createButton]; return self; } -
MyView.h
@interface Myview : UIView
@end
MyView.m
#import "MyView.h"
- (init){
self = [super init];
if(self)
[self createButton];
return self;
}
- (void) createButton{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100,100,100,50)];
[button setTitle:@"Go" forState:UIControlStateNormal];
[button addTarget:self
`action:@selector(goAction)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
- (void) goAction{
NSString *test = @"Some text";
}
MyViewController.m
- (id) init{
self = [super init];
if (self) {
MyView *myview = [[MyView alloc] init];
[self.view addSubview:myview];
}
return self;
}`
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
#import "ViewController.h"
#import "MyViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyViewController *myTestView = [[MyViewController alloc] init];
[self.view addSubview:myTestView.view];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ViewController.m
- (id) init{
self = [super init];
if (self) {
MyView *myview = [[MyView alloc] init];
[self.view addSubview:myview];
}
return self;
}`
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
#import "ViewController.h"
#import "MyViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyViewController *myTestView = [[MyViewController alloc] init];
[self.view addSubview:myTestView.view];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
单击不起作用的原因是您没有设置
MyView的frame
这样就可以了(尽管我仍然不明白为什么需要将一个ViewController添加到另一个ViewController中)
内联对象C
,为什么要以编程方式创建另一个UIViewController
(MyViewController)?为什么不直接在ViewController.m中添加MyView
?直接将MyView添加到ViewController不会有问题。但我不明白为什么在我将MyViewController添加到ViewController时它不起作用!如果将MyView直接添加到ViewController中,是否有效?是的。它很好用。