【问题标题】:Can't get programmatically made UIButton to work - iPhone无法以编程方式使 UIButton 工作 - iPhone
【发布时间】:2011-04-21 00:30:28
【问题描述】:

这是我正在使用的代码:

-(void)viewDidLoad
{
    NSString *checkerPath = [[NSBundle mainBundle] pathForResource:@"black-yellow-checker" ofType:@"png"];
    UIImage *checkerImage = [[UIImage alloc] initWithContentsOfFile:checkerPath];
    checkerView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 230.0f, 320.0f, 280.0f)];
    [checkerView setImage:checkerImage];

    UIButton *backButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    backButton.frame = CGRectMake(45.0f, 175.0f, 230.0f, 50.0f);
    [backButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"yellowButton" ofType:@"png"]] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBackHome:) forControlEvents:UIControlEventTouchDown];
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont fontWithName:@"Marker Felt" size:30];
    backButton.titleLabel.textColor = [UIColor blackColor];
    [checkerView addSubview:backButton];
}

- (void)goBackHome:(id)sender
{
    NSLog(@"go back pressed");
}

不知道为什么这不起作用。按钮出现了,但是当我按下它时没有任何反应。当我触摸它时,它甚至不会变成“缩进”图像。没有。不能使用 IB,必须以编程方式。有什么想法吗?

【问题讨论】:

    标签: iphone button uibutton


    【解决方案1】:

    UIImageView has userInteractionEnabled set to NO by default。这可以防止任何子视图被触及。

    您可以通过以下方式启用图像视图的用户交互

    checkerView.userInteractionEnabled = YES;
    

    或创建一个新的 UIView 以同时包含 checkerViewbackButton

    UIView* newView = ...
    ...
    [newView addSubview:checkerView];
    [newView addSubview:backButton];
    

    【讨论】:

    【解决方案2】:

    我相信 forControlEvents: 必须是 UIControlEventTouchUpInside。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 2016-07-09
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多