iOS - 动态按钮

Myt*_*ral 6 iphone ios ios-4.2

我正在尝试使用通过代码(没有IB)在我的项目中创建的动态按钮,它们出现在我想要的地方和方式但他们不会触发他们的行为.

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(475, 302, 49, 58);
    [button1 setTitle:@"1" 
             forState:(UIControlState)UIControlStateNormal];
    [button1 addTarget:self
                action:@selector(goToFirstTrailer) 
      forControlEvents:(UIControlEvents)UIControlEventTouchDown];
    [myImageView addSubview:button1];


-(void)goToFirstTrailer {
    [self startAnimator:@"OutsideToTrailer1_" forNumFrames:60];
}
Run Code Online (Sandbox Code Playgroud)

放置的imageView具有按钮和启用用户交互.

任何你可以流下的光都会非常感激.

Gor*_*tch 10

我认为你有行动方法改变的错误签名

-(void) goToFirstTrailer:(id)sender {

以及将动作设置为的位置

[button1 addTarget:self action:@selector(goToFirstTrailer:) forControlEvents:....

重要的是消息名称后面的冒号,因为我更改了操作方法签名以包含发件人.

编辑我用一个imageView编写了一个小示例项目,MainWindow.xib并按编程方式创建了一个按钮,如下所示

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.

    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(0.f, 0.f, 50.f, 50.f);
    [button1 setTitle:@"1" 
             forState:(UIControlState)UIControlStateNormal];
    [button1 addTarget:self
                action:@selector(goToFirstTrailer:) 
      forControlEvents:(UIControlEvents)UIControlEventTouchDown];
    imageView.userInteractionEnabled = YES; // <--- this has to be set to YES
    [imageView addSubview:button1];
    [self.window makeKeyAndVisible];

    return YES;
}
Run Code Online (Sandbox Code Playgroud)

它是快速和脏的,是的,我滥用应用程序委托作为视图控制器.我知道这很糟糕.

这是动作方法

- (void) goToFirstTrailer:(id)sender {
    imageView.backgroundColor = [UIColor redColor];
}
Run Code Online (Sandbox Code Playgroud)

在父imageView上设置userInteractionEnabled属性会产生差异.将其设置为NO(默认值),不会将任何事件路由到该按钮.