如何在swift中以编程方式添加相等宽度和相等高度约束?

时间:2015-12-11 09:48:59

标签: swift nslayoutconstraint

任何人都可以帮助我我有这个简单的视图,如果我正在使用故事板但我的所有UILabel都基于某个地方(API),这就是我需要以编程方式创建视图的原因。

这是我想要实现的观点

我目前所取得的成就是将顶部标签固定在其位置,并在标签1,2和&处添加前导空间。 3

基本上我需要的是:

  1. 将标签1固定到顶部标签
  2. 将标签3固定到底部
  3. 将垂直空格添加到标签1,2,3
  4. 在标签1,2,3
  5. 中具有相同的宽度和高度约束

    到目前为止,这是我的代码。

     private func addTopConstraint(from:AnyObject,to:AnyObject,cons:CGFloat){
       let topConstraint =  NSLayoutConstraint(item: from, attribute: .Top, relatedBy: .Equal, toItem: to, attribute: .Bottom, multiplier: 1.0, constant: cons)
        self.view.addConstraint(topConstraint)
    }
    
    private func addVerticalSpace(from:AnyObject,to:AnyObject,cons:CGFloat){
        let verticalSpace = NSLayoutConstraint(item: from, attribute: .Bottom, relatedBy: .Equal, toItem: to, attribute: .Bottom, multiplier: 1.0, constant: cons)
    
        self.view.addConstraint(verticalSpace)
    }
    private func addLeadingSpace(from:AnyObject,to:AnyObject,cons:CGFloat){
        let leadingSpace = NSLayoutConstraint(item: from, attribute: .Leading, relatedBy: .Equal, toItem: to, attribute: .Leading, multiplier: 1.0, constant: cons)
        self.view.addConstraint(leadingSpace)
    }
    
    
    
    
     private func sameWidthAndHeight (from:AnyObject,to:AnyObject){
               let width = NSLayoutConstraint(item: from, attribute: .Width, relatedBy: .Equal, toItem: to, attribute: .Width, multiplier: 1.0, constant: 0)
               let height = NSLayoutConstraint(item: from, attribute: .Height, relatedBy: .Equal, toItem: to, attribute: .Height, multiplier: 1.0, constant: 0)
    
                self.view.addConstraint(width)
                self.view.addConstraint(height)
            }
    

    sameWidthAndHeightaddVerticalSpace功能失败

    也许它与内容拥抱和优先级有关,我不确定,因为我们习惯在故事板中这样做。

    谁能分享想法?提前致谢

0 个答案:

没有答案