user2754113
user2754113

Reputation: 27

UIButton not respond in UIView

UIButton in my view does not respond when I click it. Some one figure out what I am doing wrong? Here is my entire code:

    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

Upvotes: 1

Views: 67

Answers (1)

schmidt9
schmidt9

Reputation: 4538

The reason why clicks does not work is that you don't set frame of MyView This way it works (although I still don't understand why you need to add one ViewController into another)

@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;
}

Upvotes: 1

Related Questions