我在 UIScrollView 中动态添加按钮,但有些视图只有两个按钮,有些有 10 个。我想在滚动视图中居中按钮,所以看起来不像我从左到右构建它们。我已经尝试了 SO 的几种技巧,但似乎没有任何效果。设置内容偏移量是我的第一种方法,但没有我想要的效果。
这是我正在使用的代码:
- (void)addButton:(UIButton *)button {
CGFloat contentWidth = 0.0f;
CGRect buttonFrame = button.frame;
if ([_scrollView.subviews count] == 0) {
buttonFrame.origin.x = self.contentIndicatorWidth + kButtonSeperator;
contentWidth = self.contentIndicatorWidth + buttonFrame.size.width + self.contentIndicatorWidth;
} else {
contentWidth = _scrollView.contentSize.width;
UIButton *lastButton = [_scrollView.subviews lastObject];
buttonFrame.origin.x = lastButton.frame.origin.x + lastButton.frame.size.width + kButtonSeperator;
contentWidth += buttonFrame.size.width + kButtonSeperator;
}
button.frame = buttonFrame;
[_scrollView addSubview:button];
_scrollView.contentSize = CGSizeMake(contentWidth *kContentMultiplicityFactor, _scrollView.frame.size.height);
[_buttons setValue:button forKey:button.titleLabel.text];
totalWidth = contentWidth;
// [_scrollView scrollRectToVisible:[self getButtonAtIndex:0].frame animated:YES]; }