我的 UIScrollview 很长,超过了屏幕的宽度。请参阅下面的屏幕截图以供引用。
我正在动态变化的 for 循环中以编程方式向此 ScrollView 添加按钮。有一个基本上与 ScrollView 宽度相同的“containerView”,我实际上是将按钮直接添加到它上面。那里的代码非常简单,如下所示:
for (int i=0; i<numberOfButtons; i++) {
UIButton *currentButton = [[UIButton alloc] init];
[currentButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[currentButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[currentButton setTag:i];
[currentButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.containerView addSubview:currentButton];
// here's where I programatically set constraints for positioning
}
按钮在正确的位置显示得非常好,最初出现在屏幕上的按钮(即上面截图示例中的前两个按钮)完美地触发了“buttonPressed:”方法。但是,最初在屏幕外的那些仍然可以正常显示,但点击时不会触发该事件。
我看到其他类似的帖子,但似乎没有任何效果。关于在何处进行此操作的任何想法?我有点难过。提前致谢!
最佳答案
事实证明,这个问题的答案正是 rdelmar 在他的评论中所指出的。 containerView 的框架被设置为屏幕大小的边界,所以当我将背景颜色更改为白色时,很明显边界被限制为初始屏幕宽度。
修复非常简单 - 一旦 for 循环完成,我就知道 containerView 需要多长,所以我只需将框架设置为适当的宽度。问题已解决!
关于ios - UIScrollview - 屏幕外按钮不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831691/