在 swift - xcode11 中使用 frame = bound 选项时未对齐

Mis-aligned when use frame = bound option in swift - xcode11

我是 iPhone 开发的初学者。我正在修改现有项目中的一些代码。

我在注册时有一个签名按钮,它对齐得很好。约束设置适当。 但现在我将相同的代码(Apple 登录按钮代码)添加到我的登录页面。但不是很好 居中和对齐。 下面是我用来添加苹果登录按钮的代码

 if #available(iOS 13.0, *) {
        let authorizationButton = ASAuthorizationAppleIDButton()
        
  
        authorizationButton.addTarget(self, action: #selector(handleLogInWithAppleIDButtonPress), for: .touchUpInside)
        
        authorizationButton.frame = self.appleSignInButton.bounds

        
        self.appleSignInButton.addSubview(authorizationButton)


        
    } else {
        self.appleSignInView.isHidden = true
    }

结果如下图。

但是当注册页面使用相同的代码时

两个页面的约束条件属性 也相同。

在对齐视图时不要为 frames 和 bounds 而烦恼。让 Auto Layout 通过提供适当的约束来处理:

let authorizationButton = ASAuthorizationAppleIDButton()

authorizationButton.addTarget(self, action: #selector(handleLogInWithAppleIDButtonPress), for: .touchUpInside)

self.appleSignInButton.addSubview(authorizationButton)

// Don't use the frame, place the view using constraints
authorizationButton.translatesAutoresizingMaskIntoConstraints = false

// Set the constraints after adding the view to the view hierarchy
NSLayoutConstraint.activate([
    authorizationButton.leadingAnchor.constraint(equalTo: appleSignInButton.leadingAnchor),
    authorizationButton.trailingAnchor.constraint(equalTo: appleSignInButton.trailingAnchor),
    authorizationButton.topAnchor.constraint(equalTo: appleSignInButton.topAnchor),
    authorizationButton.bottomAnchor.constraint(equalTo: appleSignInButton.bottomAnchor)
])