首页 > 解决方案 > swift - xcode11 中使用 frame = bound 选项时未对齐

问题描述

我是 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
    }

结果如下图。 上面代码的登录页面

但是当注册页面上使用相同的代码时 带有以上代码的注册页面

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

标签: iosswiftiphonexcode11

解决方案


对齐视图时不要打扰frames 和。boundsAuto 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)
])

推荐阅读