如何在iOS Swift中以编程方式创建自动布局等宽约束? [英] How to create Auto layout equal width constraint programmatically in ios swift?

查看:238
本文介绍了如何在iOS Swift中以编程方式创建自动布局等宽约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在多个视图中以编程方式赋予宽度和高度相等的约束.我通过自动布局检查google,以编程方式获得宽度和高度相等的约束,但不是完美的答案.

How to give programmatically constraints equal width and equal height with multiple views.I check google but not perfect answer for programmatically equal width and height constraints through auto layout.

我的代码如下:

  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])
    }
}

我想以编程方式添加等宽约束.

I want to add equal width constraint programmatically.

推荐答案

您可以通过以下三种方式进行操作:

You have three possible ways to do that:

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

希望它将对某人有所帮助.

hope it will help somebody.

这篇关于如何在iOS Swift中以编程方式创建自动布局等宽约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆