ios - 以编程方式使用按钮上的约束,该按钮也是以编程方式制作的

标签 ios swift facebook

我试图通过使用约束使我的 Facebook 登录按钮(屏幕截图的顶部中央)位于“注册或登录按钮”下方,但我不确定要使用哪些约束以及如何使用它们。我是 Swift 3 的新手,我还没有以编程方式完成约束,所以欢迎任何帮助!最初我只是使用 CGRect 中的 x 和 y 位置来放置按钮,但我注意到在不同的设备上,按钮不会在同一个位置,所以我现在尝试使用约束。

看起来像这样:

enter image description here

这是关于我的 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


}

enter image description here

关于ios - 以编程方式使用按钮上的约束,该按钮也是以编程方式制作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45748287/

相关文章:

ios - TableView 的 UISearchController

ios - 避免单例的最佳方法

ios - 监视文件更改时出错 : EMFILE {"code" :"EMFILE" ,"errno" :"EMFILE" ,"syscall" :"Error watching file for changes:" ,"filename": null}?

facebook - Graph Api Link - 名称、标题、描述图片未显示

ios - 如何对类变量进行可用性检查

ios - 如何从方法中快速更新 UI

ios - 以秒为单位转换 Firebase 时间戳?

facebook - 如何使用 PHP SDK 3 Conceal 代码和状态不显示在地址中

ios - UITextField 左 View 模式。从不工作

ios - 从 App Delegate 打开 Controller