UIButton addTarget在UIViewController的子类中不起作用

时间:2014-08-29 14:00:42

标签: ios objective-c uibutton

这是MyViewController.m

actionNames[0] = @"hoge";
actionNames[1] = @"piyo";

NSMutableArray *actionConts = [[NSMutableArray alloc] init]; 
for(int i=0; i<[actionNames count]; i++){
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(DEVICE_WIDTH/3 * i, 0, DEVICE_WIDTH/3, 45)];
    // actionNames is NSMutableArray
    [btn setTitle:actionNames[i] forState:UIControlStateNormal];
    [btn setUserInteractionEnabled:YES];

    actionConts[i] = btn;
}

// ↓ does not work
[actionConts[1] addTarget:self action:@selector(follow) forControlEvents:UIControlEventTouchUpInside];

// actionSubs is NSMutableArray 
for(int i=0; i<[actionConts count]/3; i++){
    actionSubs[i] = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 45)];;
}
for(int i=0; i<[actionConts count]; i++){
    int sub = floor( (float)i / 3.0 );

    [actionSubs[sub] addSubview:actionConts[i]]; 

}

UIScrollView *actionScr = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 150, 320, 45)];
[actionScr setPagingEnabled:YES];
[actionScr setShowsHorizontalScrollIndicator:NO];
[actionScr setBounces:NO];
actionScr.contentSize = CGSizeMake([actionSubs count] * DEVICE_WIDTH, 45);
for(int i=0; i<[actionSubs count]; i++){
    [actionScr addSubview:actionSubs[i]];
}
  1. 创建一个按钮。 =&GT; actionConts [N]
  2. addTarget 到actionConts [1]
  3. actionSubs [] alloc
  4. addSubView actionConts [n]到actionSubs [n]
  5. addSubView actionSubs [n] to actionScr
  6. (addSubView actionScr to drw)
    (drw是一个UIView实例。“IBOutlet UIView * drw;”)
  7. 单击此按钮时,它不起作用...(';ω;`)

    请帮帮我。 感谢。

1 个答案:

答案 0 :(得分:0)

您的代码对我来说很好。我只更换了一些行:

[actionConts[1] addTarget:self action:@selector(follow) forControlEvents:UIControlEventTouchUpInside];

替换为:

for (UIButton *button in actionConts) {
    [button addTarget:self action:@selector(follow) forControlEvents:UIControlEventTouchUpInside];
}

允许从数组中为每个按钮添加操作。

我也从以下代码中取代了for循环条件:

for(int i=0; i<[actionConts count]/3; i++)

为:

for(int i=0; i<ceil((float)[actionConts count]/3.0); i++)

允许按钮至少有一个superview。

现在follow是一种为每个按钮触发的方法。您可以设置UIButton.tag属性以阐明按下哪个属性。