UIButton在UIView中没有回复

时间:2017-05-18 12:59:13

标签: 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;
    }

    - (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.
}

ViewController.m

#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

1 个答案:

答案 0 :(得分:1)

点击不起作用的原因是您没有设置frame MyView 这种方式有效(尽管我仍然不明白为什么你需要将一个ViewController添加到另一个中)

@implementation MyViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        MyView *myview = [[MyView alloc] init];
        myview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width);
        [self.view addSubview:myview];
    }
    return self;
}