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

问题描述

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

我在注册时有一个签名按钮,对齐的很好。约束设置正确。 但是现在我在登录页面添加了相同的代码(Apple登录按钮代码)。但这不是很好 居中并对齐。 下面是我用于添加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
    }

结果如下图所示。

Login Page with above code

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

Registration Page with Above code

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

解决方法

对齐视图时,请勿打扰framebounds。让 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)
])