在我的 ViewController 中,我使用自动布局以编程方式添加了一个 UIView
这里我正在应用基于模拟器方向的约束,但这里基于我的代码约束仅在模拟器处于纵向模式时应用但在横向模式下更改它时约束不应用我在这里做错了什么
#import "MainViewController.h"
@interface MainViewController (){
UIView * MainView;
}
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
MainView = [[UIView alloc] init];
MainView.backgroundColor = [UIColor orangeColor];
MainView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:MainView];
[self AppyingAutolayoutsAtPortraint];
}
-(void)AppyingAutolayoutsAtPortraint{
NSDictionary * HeaderDictionary = NSDictionaryOfVariableBindings(MainView);
//Appliying Autolayouts for MainView
[self.view removeConstraints:self.view.constraints];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-0-[MainView]-0-|"]
options:0
metrics:nil
views:HeaderDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-0-[MainView]-0-|"]
options:0
metrics:nil
views:HeaderDictionary]];
[self.view setNeedsLayout];
}
-(void)AppyingAutolayoutsLandAtScpae{
NSDictionary * HeaderDictionary = NSDictionaryOfVariableBindings(MainView);
//Appliying Autolayouts for MainView
[self.view removeConstraints:self.view.constraints];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-10-[MainView]-10-|"]
options:0
metrics:nil
views:HeaderDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-10-[MainView]-10-|"]
options:0
metrics:nil
views:HeaderDictionary]];
[self.view setNeedsLayout];
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context){
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait) {
NSLog(@"UIInterfaceOrientationPortrait");
[self AppyingAutolayoutsAtPortraint];
}
else if (orientation == UIInterfaceOrientationLandscapeLeft) {
NSLog(@"UIInterfaceOrientationLandscapeLeft");
[self AppyingAutolayoutsLandAtScpae];
}else if (orientation == UIInterfaceOrientationLandscapeRight){
NSLog(@"UIInterfaceOrientationLandscapeRight");
[self AppyingAutolayoutsLandAtScpae];
}
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
}];
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}
@end
答案 0 :(得分:2)
您可以根据需要使用尺寸等级。使用大小类,在设计应用程序时,您现在可以创建单个布局,该布局适用于所有当前的iOS设备 - 没有狡猾的平台特定代码。您需要做的就是打开故事板,转到文件检查器并确保勾选使用大小类复选框。
答案 1 :(得分:0)
在UIInterfaceOrientationLandscapeLeft和UIInterfaceOrientationLandscapeRight中调用2个不同的函数
这似乎毫无意义:
else if (orientation == UIInterfaceOrientationLandscapeRight){
NSLog(@"UIInterfaceOrientationLandscapeRight");
[self AppyingAutolayoutsAtPortraint]; //?
}