我对xCode 4.5的新的自动布局功能感到非常困惑。
这是我想做的,
通过设置故事板,我设置了这个肖像视图。
通过使用自动收费表和约束(和引脚),当布局翻转到这样的景观时,我如何转换它?
我尝试编码和改变CGRect(大小和坐标位置)的视图时,它的美化,但没有任何效果。
发布于 2013-05-24 07:46:13
NSLayoutConstraints取代了自动布局中对CGRects的需求。首先,用文字描述你的布局。下面是我描述你肖像的例子:
下面是一种删除superview
现有约束的方法,然后为给定的接口方向应用新的约束。
- (void) buildConstriantsForInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Remove existing constraints.
[superview removeConstraints:superview.constraints] ;
// Build an array to hold new constraints.
NSMutableArray* constraints = [NSMutableArray new] ;
// Add 2 constraints that apply to both Portrait & Landscape orientations.
[constraints addObject:[NSLayoutConstraint constraintWithItem:red attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeWidth multiplier:0.6 constant:0]] ;
[constraints addObject:[NSLayoutConstraint constraintWithItem:blue attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeHeight multiplier:0.55 constant:0]] ;
// Build a dictionary to store references to NSViews.
NSDictionary* views = NSDictionaryOfVariableBindings(superview, blue, red, yellow) ;
// To eliminate repeated NSLayoutConstraint code, build an array of Format Strings with which to build constraints.
NSArray* formatStrings ;
if ( UIInterfaceOrientationIsPortrait(interfaceOrientation) ) {
formatStrings = @[@"H:|[blue]|", @"H:|[red]-[yellow]|", @"V:|[blue]-[red]|", @"V:[blue]-[yellow]|"] ;
}
else {
formatStrings = @[@"H:|[blue]-[yellow]|", @"H:|[red]-[yellow]", @"V:|[blue]-[red]|", @"V:|[yellow]|"] ;
}
for ( NSString* formatString in formatStrings ) {
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:formatString options:0 metrics:nil views:views]] ;
}
// Add the newly created constraints.
[superview addConstraints:constraints] ;
}
每当视图加载或旋转时,都可以调用该方法。
-(void) viewDidLoad {
superview.translatesAutoresizingMaskIntoConstraints = NO ;
[self buildConstriantsForInterfaceOrientation:self.interfaceOrientation] ;
}
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[self buildConstriantsForInterfaceOrientation:toInterfaceOrientation] ;
}
发布于 2013-05-24 07:46:04
Autolayout擅长表达一个对象与另一个对象之间的关系并解决冲突,但它没有内置任何条件概念。对于您的布局,我认为您可能会发现添加和删除旋转约束是最简单的,请查看Class/NSLayoutConstraint/NSLayoutConstraint.html以了解如何添加这些约束的详细信息。
你也可以设置你的约束和调整优先级,以便它在旋转时做正确的事情,但它将需要一些测试和调整才能使它正确运行。我在本地做了一些测试,我认为我让它做了正确的事情,但这只是一个没有固有内容大小的空视图。尽管如此,我认为这是通过故事板来完成这一切的必要条件:
我认为这是从蓝色视图开始,蓝色视图具有相当高的优先级最大大小,黄色视图知道如何向上扩展,但优先级较低。当它旋转时,蓝色视图保持其最大大小,这将释放黄色视图以向上扩展。然后,我填写所需的约束,以使事情保持一致。
这是相当复杂的文字描述,这里有一个屏幕抓取显示三个视图和它们之间的限制。它并不能显示一切,但至少可以查看视图之间的关系:
https://stackoverflow.com/questions/16730720
复制相似问题