Search code examples
iosswiftiphonexcode11

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


I am beginner to iPhone development. I am modifying some code in existing project.

I have a signing button on registration when which is aligned well. constraint set proper. but now I added same code (Apple Sign in button code) to my login Page. but it is not well centered and align. here below is code which I am using for add apple signin button

 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
    }

And Result is as below Image. Login Page with above code

But when same code used on registration page Registration Page with Above code

Constraint property also same for both pages.


Solution

  • Don't bother with frames and bounds when aligning views. Let Auto Layout handle that by giving proper constraints:

    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)
    ])