这是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]];
}
单击此按钮时,它不起作用...(';ω;`)
请帮帮我。 感谢。
答案 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
属性以阐明按下哪个属性。