【问题标题】:Tap method on UIButton when its a sub view of UIView not working当 UIView 的子视图不起作用时,在 UI Button 上点击方法
【发布时间】:2015-08-19 21:33:29
【问题描述】:

点击 UIButton 时出现 EXC_BAD_ACCESS 错误。如果我将逻辑移动到RootViewController.m 它可以工作,但在我的PanelViewController.m 中实现时则不行。我不明白为什么这不起作用,我缺少什么以及如何使它起作用?

RootViewController.m

#import "RootViewController.h"
#import "PanelViewController.h"

@interface ListViewRootController ()

@end

@implementation ListViewRootController
    - (void)viewDidLoad {
        [super viewDidLoad];

        [self.view setFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
        [self.view setBackgroundColor:[UIColor blueColor]];

        PanelViewController *panelView = [[PanelViewController alloc] init];

        [self.view addSubview:panelView.view];
    }
@end

PanelViewController.m

#import "PanelViewController.h"

@interface PanelViewController ()

@end

@implementation PanelViewController
    - (void)viewDidLoad {
        [super viewDidLoad];

        UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
        topBar.backgroundColor = [UIColor whiteColor];

        UIButton *mapButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, topBar.frame.size.height)];
        [mapButton setTitle:@"Map" forState:UIControlStateNormal];
        [mapButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [mapButton addTarget:self action:@selector(mapViewToggle:) forControlEvents:UIControlEventTouchDown];

        [self.view addSubview:topBar];
        [topBar addSubview:mapButton];
    }

    - (void)mapViewToggle:(UIButton *)sender{
         NSLog(@"hello, is it me youre looking for");
    }
@end

【问题讨论】:

    标签: ios objective-c uiview uibutton subview


    【解决方案1】:

    是的,不行,panelView控制器在这之后被释放

    PanelViewController *panelView = [[PanelViewController alloc] init];
    

    你应该在 RootViewController 的 .h 中有一个 var,类似于

    @interface RootViewController : UIViewController {
      PanelViewController *panelView;
    }
    

    然后:

         panelView = [[PanelViewController alloc] init];
    
         [self.view addSubview:panelView.view];
    

    【讨论】:

    • 谢谢!这是完全有道理的。我现在已经修复它并且它现在按预期工作:)
    猜你喜欢
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    相关资源
    最近更新 更多