自動レイアウトを使用して iOS6 の UIScrollView に苦労しています。私がやろうとしているのは、多数のサブビュー (UIView) を保持するスクロールビューを設定することです。これらのサブビューは、ループ内で動的に作成されます。自動レイアウトで動作するように、制約を追加したいと思います。
viewDidLoad で、次のコードを取得しました。
scrollView.pagingEnabled = YES;
CGRect selfBounds = self.view.bounds;
CGFloat width = CGRectGetWidth(self.view.bounds);
CGFloat height = CGRectGetHeight(self.view.bounds);
NSMutableString *constraintBuilding = [NSMutableString stringWithFormat:@"|"];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
CGFloat offset = width * i;
UIView* view1 = [[UIView alloc] initWithFrame:CGRectOffset(selfBounds, offset, 0)];
[view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view1 setBackgroundColor:[colors objectAtIndex:i]];
[scrollView addSubview:view1];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view1(height)]|" options:0 metrics:@{@"height":@(height)} views:NSDictionaryOfVariableBindings(view1)]];
[constraintBuilding appendString:[NSString stringWithFormat:@"[view%i(width)]",i+1]];
}
NSMutableArray *views = [[NSMutableArray alloc] init];
for (int j = 0; j < scrollView.subviews.count; j++) {
if (![[scrollView.subviews objectAtIndex:j] isKindOfClass:[UIImageView class]]) {
[views addObject:[scrollView.subviews objectAtIndex:j]];
}
}
[constraintBuilding appendString:@"|"];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraintBuilding options:0 metrics:@{@"width":@(width*colors.count)} views:NSDictionaryOfVariableBindings(views)]];
ループは正常に機能しますが、最後の行でエラーが発生します
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraintBuilding options:0 metrics:@{@"width":@(width*colors.count)} views:NSDictionaryOfVariableBindings(views)]];
constraintBuilding は " |[view1(width)][view2(width)][view3(width)]| " と言います。
それは例外です:
'NSInvalidArgumentException', reason: 'Unable to parse constraint format:
view1 はビュー ディクショナリのキーではありません。|[view1(幅)][view2(幅)][view3(幅)]| ^'
テストのために、色の配列に 3 つのオブジェクトがありますが、後でこの数は動的に変化します。
ご協力いただきありがとうございます!
クリス
編集:
もう一つ。この記事を読んで、うまくいきました。残念ながら、動的な数のビューを持つループにはありません。:(
と
この記事はアップルから読みました。それでも私は自分の答えを見つけることができませんでした。