ios 查看.topAnchor和查看.safeAreaLayoutGuide.topAnchor之间有什么区别?

jq6vz3qz  于 2023-01-14  发布在  iOS
关注(0)|答案(2)|浏览(164)

我一直在Swift for iOS中处理约束,文档在解释事情方面做得很好。
但是,最近有一件事让我感到困惑,那就是view.topAnchorview.safeAreaLayoutGuide.topAnchor之间的区别。
当我在iOS应用程序中以编程方式设置约束时,我发现我可以完全互换使用这些约束,所以我无法区分两者之间的区别。
我查看了www.example.com上的文档developer.apple.com,没有找到任何解释差异的内容。
这两种性质有什么区别吗?

mwkjh3gx

mwkjh3gx1#

主要的区别是与设备有一流的屏幕,以及像iPhone 11的主页按钮在你的视野内,而不是像iPhone 8和更老的物理按钮。也正如它所说,它让你在安全区域,即使设备在横向旋转,但有些设计需要使用顶部锚。

nzk0hqpo

nzk0hqpo2#

UIView.topAnchor表示视图框架的上边缘。
UIView.safeLayoutGuide是一个矩形区域,表示视图的安全区域,即视图中未被条形图和其他内容遮挡的部分。
UIView.safeLayoutGuide.topAnchorUIView.safeLayoutGuide的上边缘。
示例:
尝试在Xcode中创建一个空的storyboard项目,用下面的代码修改"ViewController. m"。这段代码创建红色的topView和bottomView,它们位于父视图内部,但在视图的safeArea之外。

#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]
  ]];
}

示例部分截图:(请忽略按钮)

相关问题