我的应用程序中有 10 个 UIButtons 并排堆叠,按钮的总尺寸为 640x96。
如果我直接将这些按钮添加到 UIScrollView,它们会注册触摸事件并且可以滚动。
但是,如果我尝试将它们添加到普通 UIView,然后将该 UIView 添加到 ScrollView ,它们将不起作用。
这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *fview = [[UIView alloc] init];
fview.frame = CGRectMake(0, 0, 640, 96);
fview.backgroundColor = [UIColor blackColor];
[fview setUserInteractionEnabled:YES];
[_sv setUserInteractionEnabled:YES];
for (int i=0; i<10; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(64*i, 0, 64, 96);
[button setTitle:@"Click Me!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[fview addSubview:button];
}
[_sv addSubview:fview];
_sv.contentSize = CGSizeMake(640, 96);
}
-(void)buttonClicked:(id)sender {
NSLog(@"Clicked!");
}
最佳答案
当我写问题时,我解决了问题:D
我所要做的就是在设置 ScrollView 的内容大小之前设置 UIView 的框架。
就我而言:
[_sv addSubview:fview];
fview.frame = CGRectMake(0, 0, 640, 96); // Added line
_sv.contentSize = CGSizeMake(640, 96);
希望这有帮助!
关于ios - UIButtons 在直接添加到 ScrollView 但不是间接添加时接收触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18109102/