gpt4 book ai didi

objective-c - UIScrollView 中的中心行按钮

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:17:21 25 4
gpt4 key购买 nike

我在 UIScrollView 中动态添加按钮,但有些 View 只有两个按钮,有些有 10 个。我想在 ScrollView 中将按钮居中,这样看起来我不是从左到右构建它们的。我已经尝试了 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];

最佳答案

添加按钮后调用此方法:


- (void)centerButtons:(NSArray*)buttons {
CGSize scrollViewSize = _scrollView.bounds.size;

// Measure the total width taken by the buttons
CGFloat width = 0;
for (UIButton* b in buttons)
width += b.bounds.size.width + kButtonSeparator;
if (width > kButtonSeparator)
width -= kButtonSeparator;

// If the buttons width is shorter than the visible bounds, adjust origin
CGFloat origin = 0;
if (width < scrollViewSize.width)
origin = (scrollViewSize.width - width) / 2.f;

// Place buttons
CGFloat x = origin;
CGFloat y = 0;
for (UIButton* b in buttons) {
b.center = CGPointMake(x + b.bounds.size.width/2.f, y + b.bounds.size.height/2.f);
x += b.bounds.size.width + kButtonSeparator;
}

_scrollView.contentSize = CGSizeMake(MAX(scrollViewSize.width, width), scrollViewSize.height);
}

关于objective-c - UIScrollView 中的中心行按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13808051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com