swift - 以编程方式约束按钮

标签 swift xcode button

我希望我的按钮保持在 x 轴中心,但我想在 y 轴上调整它。我的按钮是通过编程制作的,但我的注册页面主要是在 Storyboard上构建的。这使得按钮看起来与其他所有东西都不同

 super.viewDidLoad()


    button = dropDownBtn.init(frame: CGRect(x:0, y:0, width:0, height: 0))
    button.setTitle("BusinessType", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(button)

    PROBLEM !!!!!
    //button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

    //button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

    button.widthAnchor.constraint(equalToConstant: 200).isActive = true
    button.heightAnchor.constraint(equalToConstant: 40).isActive = true
    button.self.layer.cornerRadius = 10

    button.dropView.dropDownOptions = ["Apparel", "Artist", "Beauty", "Cosmetology", "Fitness", "Resturant","Photography"]

最佳答案

重新注释centerXAnchorcenterYAnchor约束

NSLayoutConstraint.activate([
  button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
  button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor,constant:-200), 
  button.widthAnchor.constraint(equalToConstant: 200),
  button.heightAnchor.constraint(equalToConstant: 40) 
])

关于swift - 以编程方式约束按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57227543/

相关文章:

ios - 在 IOS 中单击时更改按钮文本和背景颜色

javascript - 我希望通过按钮更改文本。不能放图片什么的

swift 4 : generic conforming to AnyObject does not accept a protocol conforming to AnyObject

ios - 如何使用 expectationForPredicate 并点击一个按钮

ios - 在我滚动之前 UICollectionView 没有完全加载

ios - iOS 8 中编译图像资源的大小增加

ios - 如何在一个 View Controller 中使用两个自定义 UITableViewCells 创建两个 TableView ?

ios - 使用 segue 导航到另一个 Controller

ios - xcode ld : 64-bit LDR/STR not 8-byte aligned

c# - 如何让计时器运行 10 分钟然后禁用按钮?