我在UIScrollView中動態添加按鈕,但一些視圖只有兩個按鈕,一些有10個按鈕。我想將按鈕居中在滾動視圖中,所以看起來並不像我構建它們從左到右。我已經嘗試過幾個技巧,但似乎沒有任何工作。設置內容偏移量是我的第一個方法,但沒有我想要的效果。UIScrollView中按鈕的中心排
這裏是我使用的代碼:
- (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:[自getButtonAtIndex:0] .frame動畫:YES]; }
你直接添加到UIButtons UIScrollView的或添加它變成一個UIView,然後將它添加到的UIScrollView? –
我直接將按鈕添加到滾動視圖中,如上面的代碼中所示。 – chrislhardin
要形成每一行按鈕,您將發送單獨的NSArray按鈕,如第一行3按鈕,第二行10按鈕和第三行6按鈕。我對麼? –