如何在ios swift中以编程方式创建自动布局等宽度约束?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在ios swift中以编程方式创建自动布局等宽度约束?相关的知识,希望对你有一定的参考价值。
如何以多个视图给出编程约束相等的宽度和相等的高度。我通过自动布局检查谷歌但不是完美的答案,以编程相同的宽度和高度约束。
我的代码如下所示:
var countNoOfViews:Int = 3
@IBOutlet var viewForRow1: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.specialButtonViewLeft()
}
func specialButtonViewLeft(){
for i in 0..<countNoOfViews{
var customView:UIView!
customView = UIView(frame: CGRect.zero)
customView.translatesAutoresizingMaskIntoConstraints = false
viewForRow1.addSubview(customView)
let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal,toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0)
let topConstraint = NSLayoutConstraint(item: customView, attribute: .top, relatedBy: .equal,toItem: self.viewForRow1, attribute: .top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: customView, attribute: .bottom, relatedBy: .equal,toItem: self.viewForRow1, attribute: .bottom, multiplier: 1.0, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: customView, attribute: .leading, relatedBy: .equal, toItem: self.viewForRow1, attribute: .leading, multiplier: 1, constant: customLeadingSpaceLeft)
customLeadingSpaceLeft = customLeadingSpaceLeft + customViewWidth
arrayLeftBtnConstraints.append(widthConstraint)
if i == 0{
customView.backgroundColor = UIColor.red
}else if i == 1{
customView.backgroundColor = UIColor.green
}else if i == 2{
leftViewVal = customLeadingSpaceLeft
customView.backgroundColor = UIColor.black
}
customView.alpha = 0.50
viewForRow1.addConstraints([widthConstraint, leadingConstraint,topConstraint,bottomConstraint])
}
}
我想以编程方式添加等宽度约束。
您有三种可能的方法:
1)使用锚点:
view.widthAnchor.constraint(equalTo: otherView.widthAnchor, multiplier: 1.0).isActive = true
2)视觉格式:
简单的例子 - "H:|[otherView]-[view(==otherView)]|"
3)“老派”限制:
NSLayoutConstraint(item: #view, attribute: .width, relatedBy: .equal, toItem: #otherView, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true
希望它会帮助某人。
试试这个:
let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: viewForRow1, attribute: .width, multiplier: 0.25, constant: 0.0)
multiplier: 0.25
,表示customView
的宽度将是父视图的1/4,viewForRow1
。
以上是关于如何在ios swift中以编程方式创建自动布局等宽度约束?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用自动布局在 ios 中以编程方式在 UIview 上添加 UIbutton
有啥方法可以在 Swift 中以编程方式获取所有应用的自动布局约束
iOS - 在 Swift 3 中以编程方式删除和激活新约束时布局损坏