【问题标题】:Constraint between UIButton and UIViewUIButton 和 UIView 之间的约束
【发布时间】:2020-08-04 15:29:38
【问题描述】:

enter image description here我是 Swift 开发的新手,距离我尝试解决我面临的这个问题已经过去了几个小时。错误在于约束。下面是我的代码:


// 我的约束代码

skipButtonAnchor = skipButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.leadingAnchor, bottom: nil, right: view.trailingAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
    
bottomStackAnchor = bottomStack.anchor(nil, left: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.trailingAnchor, topConstant: 0, leftConstant: 125, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)

// 我已经为 .anchor 创建了这样的函数:

func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
        translatesAutoresizingMaskIntoConstraints = false
}

我期待着寻求帮助。提前致谢

【问题讨论】:

  • “我面临的问题”是什么?

标签: swift uiview uibutton nslayoutconstraint terminate


【解决方案1】:

“我是 Swift 开发新手” --- 因为你是新手,我高度建议使用标准约束语法,直到您已经了解了约束和自动布局的工作原理。 那么如果您觉得有帮助,请使用“辅助函数”。

试试这样:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // setup properties for skipButton and bottomStack
    // ...
    // add subviews to bottomStack
    // ...
    
    view.addSubview(skipButton)
    view.addSubview(bottomStack)
    
    skipButton.translatesAutoresizingMaskIntoConstraints = false
    bottomStack.translatesAutoresizingMaskIntoConstraints = false
    
    // respect safe area
    let g = view.safeAreaLayoutGuide
    
    NSLayoutConstraint.activate([
        
        // constrain skipButton Top / Leading / Trailing (to safe area)
        skipButton.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
        skipButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
        skipButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
        
        // constrain skipButton Height = 50
        skipButton.heightAnchor.constraint(equalToConstant: 50.0),
        
        // constrain bottomStack Leading to Leading (safe-area) + 125
        bottomStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 125.0),

        // constrain bottomStack Trailing / Bottom (to safe-area)
        bottomStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
        bottomStack.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),

        // constrain bottomStack Height = 50
        bottomStack.widthAnchor.constraint(equalToConstant: 50.0),
        
    ])

}

【讨论】:

  • 感谢您的帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 2020-07-02
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多