【问题标题】:UIButton not respond in UIViewUIButton 在 UIView 中没有响应
【发布时间】:2017-05-18 12:59:12
【问题描述】:

当我单击它时,我认为 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

【问题讨论】:

  • 内联Object C,
  • 为什么要以编程方式创建另一个UIViewController (MyViewController)?为什么不在 ViewController.m 中直接添加MyView
  • 直接将MyView加入ViewController是没有问题的。但是我不明白为什么当我将 MyViewController 添加到 ViewController 时它不起作用!
  • 直接把MyView加到ViewController上能用吗?
  • 是的。它工作正常。

标签: objective-c uiview


【解决方案1】:

点击不起作用的原因是你没有设置frame of 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;
}

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多