1

In my app, I need to parse some data from the network, and add some customized buttons. Later, when user click on it, I would provide more details.

  • An image view is the background for the app
  • The position of these buttons(xPos, yPos) are parsed from the server(dynamic data)
  • no prints when I click on these buttons that I add programmatically

The code I have for adding it is like this

    ...
    [businessButton setImage:businessImage forState:UIControlStateNormal];
    [businessButton setFrame:CGRectMake([xPos floatValue], [yPos floatValue], [businessImage size].width/2, [businessImage size].width/2)];
    [businessButton addTarget:self.imageView action:@selector(serviceProviderSelected:) forControlEvents:UIControlEventTouchUpInside];
    ...

- (void)serviceProviderSelected:(id)sender
{
    NSLog(@"sp tapped\n");
}

I created another dummy app to do (what I think is the same thing), and the button works out fine...

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIButton *customizedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"business-icon.png"];
    [customizedButton setImage:image forState:UIControlStateNormal];
    [customizedButton setFrame:CGRectMake(100, 100, 20, 20)];
    [customizedButton addTarget:self action:@selector(customButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:customizedButton];
}

- (IBAction)buttonPressed:(id)sender {
    NSLog(@"yes, pressed\n");
}

I've been suspecting that the buttons I create in code are already released, and printed out the array that I use for storing these Buttons, they are valid addresses though...

Thanks!

William

4

3 回答 3

1

我才知道为什么。

而不是[self.imageView addSubview:businessButton];,[self.view addSubview:businessButton];现在可以工作了。

我想我并没有真正理解在情节提要中添加 imageView 后视图关系如何。

于 2012-12-25T01:43:02.837 回答
1

UIImageView 默认禁用用户交互。您必须将此属性设置为 YES 才能获得 UIButton 或其他任何作为子视图工作的东西

于 2013-02-12T13:29:48.420 回答
0

你需要做:

[businessButton addTarget:self action:@selector(serviceProviderSelected:) forControlEvents:UIControlEventTouchUpInside];

目标需要是定义选择器的类。

于 2012-12-25T01:37:21.330 回答