我试图通过使用约束使我的 Facebook 登录按钮(屏幕截图的顶部中央)位于“注册或登录按钮”下方,但我不确定要使用哪些约束以及如何使用它们。我是 Swift 3 的新手,我还没有以编程方式完成约束,所以欢迎任何帮助!最初我只是使用 CGRect 中的 x 和 y 位置来放置按钮,但我注意到在不同的设备上,按钮不会在同一个位置,所以我现在尝试使用约束。
看起来像这样:
这是关于我的 viewDidLoad 中的按钮的代码:
let fbLoginButton = FBSDKLoginButton()
view.addSubview(fbLoginButton)
fbLoginButton.frame = CGRect(x: 0, y: 0, width: view.frame.width -
100, height: 40)
self.view.addSubview(fbLoginButton)
fbLoginButton.center.x = view.frame.width/2
我试过:
let verticalSpace = NSLayoutConstraint(
item: self, attribute: .bottom, relatedBy: .equal, toItem: fbLoginButton,
attribute: .bottom, multiplier: 0.75, constant: 0)
但这导致我得到这个错误:
Constraint items must each be an instance of UIView, or UILayoutGuide.
最佳答案
尝试代码我在使用 Storyboard添加的“显示警报”按钮下方以编程方式添加了一个“发送”按钮
@IBOutlet weak var showAlertButton: UIButton!
func AddButton(){
let sendButton = UIButton(type: .system)
sendButton.setTitle("Send", for: UIControlState())
sendButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(sendButton)
sendButton.leftAnchor.constraint(equalTo: showAlertButton.leftAnchor, constant: 0).isActive = true
sendButton.rightAnchor.constraint(equalTo: showAlertButton.rightAnchor, constant: 0).isActive = true
sendButton.topAnchor.constraint(equalTo: showAlertButton.bottomAnchor, constant: 10).isActive = true
sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
sendButton.heightAnchor.constraint(equalTo: showAlertButton.heightAnchor).isActive = true
}
关于ios - 以编程方式使用按钮上的约束,该按钮也是以编程方式制作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45748287/