我接受了@robmayoff 的建议,并将我的按钮创建移到了代码中,它奇迹般地起作用了。(我担心自动布局对我来说仍然是希腊语,但我以某种方式管理它。)如果将来有人需要创建按钮的滚动列表,这是一种不涉及contentSize
明确设置的方法,如果比IB丑一点。
self.toolbarScrollView.translatesAutoresizingMaskIntoConstraints = NO;
NSMutableArray *toolbarItems = [NSMutableArray array];
//Unfortunately, you'll have to set the contentWidth manually - in viewDidLoad
// the frames aren't set yet. 47.0 is the size (38) + margin (9) of one of my
// buttons.
CGFloat x = contentWidth - 47.0;
//This code lets you page the scroll view with more spacing between items on
//different pages.
int itemCountPerPage = 5;
NSArray *images = @[/*...titles of images...*/];
SEL selectors[10] = {
//button selectors
};
UIButton *lastButton = nil;
for (int i = 0; i < [images count]; i++)
{
NSString *imageName = [images objectAtIndex:i];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.translatesAutoresizingMaskIntoConstraints = NO;
[button setImage:[UIImage imageNamed:imageName maskedWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
button.showsTouchWhenHighlighted = YES;
if (selectors[i] != NULL)
[button addTarget:self action:selectors[i] forControlEvents:UIControlEventTouchUpInside];
[self.toolbarScrollView addSubview:button];
[toolbarItems addObject:button];
if (lastButton)
{
NSDictionary *dict = NSDictionaryOfVariableBindings(lastButton, button);
[self.toolbarScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:[lastButton(==38)]-%g-[button(==38)]-%g-|", (i % itemCountPerPage == 0 ? 18.0 : 9.0), x] options:NSLayoutFormatAlignAllCenterY metrics:nil views:dict]];
[self.toolbarScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-4-[button(==38)]-4-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:dict]];
}
else
{
NSDictionary *dict = NSDictionaryOfVariableBindings(button);
[self.toolbarScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-9-[button(==38)]-%g-|", x] options:NSLayoutFormatAlignAllCenterY metrics:nil views:dict]];
[self.toolbarScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-4-[button(==38)]-4-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:dict]];
}
x -= (i % itemCountPerPage == itemCountPerPage - 1 ? 56.0 : 47.0); //Extra space to allow for paging
lastButton = button;
}
我希望这对某人有所帮助,因为它确实给简单的滚动视图带来了很多麻烦!谢谢你的帮助。