我需要應用NSLayoutConstraints UIImageView裏面的UIView。我嘗試以編程方式執行此操作,但遇到無法同時滿足約束條件的錯誤。如何在UIView中使用UIImageView並應用NSLayoutConstraint?
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
containerView.backgroundColor = [UIColor greenColor];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,50,50)];
imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:containerView];
[containerView addSubview:imageView];
NSDictionary *views = [NSDictionary dictionaryWithObjectsAndKeys:
containerView,@"contrainerview",
imageView, @"myimageview",
nil];
containerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-(100)-[contrainerview(300)]->=0-|"] options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|[contrainerview(300)]->=0-|"] options:0 metrics:nil views:views]];
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-(100)-[myimageview]->=0-|"] options:0 metrics:nil views:views]];
2015-01-09 14:36:52.476 test[543:6554] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "" )
Will attempt to recover by breaking constraint
Make a symbolic breakpoint at
UIViewAlertForUnsatisfiableConstraints
to catch this in the debugger. The methods in theUIConstraintBasedLayoutDebugging
category onUIView
listed in<UIKit/UIView.h>
may also be helpful.
請在問題中包含錯誤 – danh
我添加了錯誤。此行導致了以下錯誤:[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@「V:| - (100) - [myimageview] - > = 0- |」] options:0 metrics:nil views:views]] ; – iamarnold