程序化自动布局约束到Superview的边缘 [英] Programmatic Auto Layout Constraints to Edges of Superview
本文介绍了程序化自动布局约束到Superview的边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在Xcode的故事板编辑器中完成了很多自动布局,但是我很少在代码中做任何事情.在一个特定的实例中,我需要创建与这些约束等效的程序设计:
I have done quite a bit of auto layout in Xcode's storyboard editor, but I rarely ever do anything in code. In one particular instance, I need to create the programmatic equivalent to these constraints:
这些约束已添加到 textView
中,而超级视图是另一个名为 commentBox
的视图.到目前为止,我已经尝试过了,但是代码感到多余,并导致约束冲突的自动布局错误:
These constraints are added to textView
and the superview is another view called commentBox
. I've tried this so far, but the code feels redundant and results in an auto layout error of conflicting constraints:
//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))
知道我在做什么错吗?谢谢!
Any idea what am I doing wrong? Thanks!
推荐答案
尝试一下:
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
这篇关于程序化自动布局约束到Superview的边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文