我在 Xcode 的 Storyboard 编辑器中做了很多自动布局,但我很少用代码做任何事情。在一个特定实例中,我需要创建与这些约束等效的程序:
这些约束被添加到 textView
并且父 View 是另一个名为 commentBox
的 View 。到目前为止,我已经尝试过了,但代码感觉多余,并导致约束冲突的自动布局错误:
//Trailing
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .trailing, relatedBy: .equal, toItem: cell.commentBox, attribute: .trailing, multiplier: 1, constant: 15))
//Leading
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .leading, relatedBy: .equal, toItem: cell.commentBox, attribute: .leading, multiplier: 1, constant: 15))
//Bottom
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: cell.commentBox, attribute: .bottom, multiplier: 1, constant: 10))
//Top
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: cell.commentBox, attribute: .top, multiplier: 1, constant: 10))
知道我做错了什么吗?谢谢!
最佳答案
试试这个:
commentBox.addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.topAnchor.constraint(equalTo: commentBox.topAnchor, constant: 10).isActive = true
textView.bottomAnchor.constraint(equalTo: commentBox.bottomAnchor, constant: -10).isActive = true
textView.leadingAnchor.constraint(equalTo: commentBox.leadingAnchor, constant: 15).isActive = true
textView.trailingAnchor.constraint(equalTo: commentBox.trailingAnchor, constant: -15).isActive = true
关于swift - 对 Superview 边缘的编程自动布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566517/