我一直在Swift for iOS中处理约束,文档在解释事情方面做得很好。但是,最近有一件事让我感到困惑,那就是view.topAnchor和view.safeAreaLayoutGuide.topAnchor之间的区别。当我在iOS应用程序中以编程方式设置约束时,我发现我可以完全互换使用这些约束,所以我无法区分两者之间的区别。我查看了www.example.com上的文档developer.apple.com,没有找到任何解释差异的内容。这两种性质有什么区别吗?
view.topAnchor
view.safeAreaLayoutGuide.topAnchor
mwkjh3gx1#
主要的区别是与设备有一流的屏幕,以及像iPhone 11的主页按钮在你的视野内,而不是像iPhone 8和更老的物理按钮。也正如它所说,它让你在安全区域,即使设备在横向旋转,但有些设计需要使用顶部锚。
nzk0hqpo2#
UIView.topAnchor表示视图框架的上边缘。UIView.safeLayoutGuide是一个矩形区域,表示视图的安全区域,即视图中未被条形图和其他内容遮挡的部分。UIView.safeLayoutGuide.topAnchor是UIView.safeLayoutGuide的上边缘。示例:尝试在Xcode中创建一个空的storyboard项目,用下面的代码修改"ViewController. m"。这段代码创建红色的topView和bottomView,它们位于父视图内部,但在视图的safeArea之外。
UIView.topAnchor
UIView.safeLayoutGuide
UIView.safeLayoutGuide.topAnchor
#import "ViewController.h" @interface ViewController() @property UIView* topView; @property UIView* bottomView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self.view setTranslatesAutoresizingMaskIntoConstraints:NO]; self.topView = [[UIView alloc] init]; [self.topView setTranslatesAutoresizingMaskIntoConstraints:NO]; self.topView.backgroundColor = [UIColor redColor]; [self.view addSubview:self.topView]; [NSLayoutConstraint activateConstraints:@[ [self.topView.topAnchor constraintEqualToAnchor:self.view.topAnchor], [self.topView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor], [self.topView.widthAnchor constraintEqualToAnchor:self.view.widthAnchor], ]]; self.bottomView = [[UIView alloc] init]; [self.bottomView setTranslatesAutoresizingMaskIntoConstraints:NO]; self.bottomView.backgroundColor = [UIColor redColor]; [self.view addSubview:self.bottomView]; [NSLayoutConstraint activateConstraints:@[ [self.bottomView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor], [self.bottomView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor], [self.bottomView.widthAnchor constraintEqualToAnchor:self.view.widthAnchor] ]]; }
示例部分截图:(请忽略按钮)
2条答案
按热度按时间mwkjh3gx1#
主要的区别是与设备有一流的屏幕,以及像iPhone 11的主页按钮在你的视野内,而不是像iPhone 8和更老的物理按钮。也正如它所说,它让你在安全区域,即使设备在横向旋转,但有些设计需要使用顶部锚。
nzk0hqpo2#
UIView.topAnchor
表示视图框架的上边缘。UIView.safeLayoutGuide
是一个矩形区域,表示视图的安全区域,即视图中未被条形图和其他内容遮挡的部分。UIView.safeLayoutGuide.topAnchor
是UIView.safeLayoutGuide
的上边缘。示例:
尝试在Xcode中创建一个空的storyboard项目,用下面的代码修改"ViewController. m"。这段代码创建红色的topView和bottomView,它们位于父视图内部,但在视图的safeArea之外。
示例部分截图:(请忽略按钮)